473,785 Members | 3,142 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete comments in .c file

I want to delete all comments in .c file.

Size of .c file is very big.

Any good idea to do this?

Please show me example code.

Nov 13 '05
39 16799
Irrwahn Grausewitz <ir*******@free net.de> writes:
Stephen Samuel <st************ @telus.net> wrote:
Here's a perl script which will handle *MOST* sane C code...

<snip>

Since when is perl topical in c.l.c?


This is an interesing edge case with respect to topicality. One could
argue that we're talking *about* C (which is clearly topical), but
we're using a mixture of Perl and English to discuss it. Think of the
Perl regular expression as a description of how to strip comments from
C source code.

On the other hand, not everyone here can be expected to speak Perl
regexps fluently.

--
Keith Thompson (The_Other_Keit h) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #31
Stephen Samuel <st************ @telus.net> wrote:
CBFalconer wrote:
*** rude top-posting fixed ***
Hmm.. This must be a relatively recent addition to usenet
ettiquete (i.e. in the last decade or so).


It's a convention in comp.lang.c (and several other technical
newsgroups) to place your comments after the part of the original
post you are responding to, in order to retain context. Thus
top-posting is discouraged in c.l.c.
Appologies. I'm an old foggie, and it's probably been an decade
since I've posted here.


Again, please do not send email copies of your replies; thank you.

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #32
Keith Thompson <ks*@cts.com> wrote:
Irrwahn Grausewitz <ir*******@free net.de> writes:

Since when is perl topical in c.l.c?
This is an interesing edge case with respect to topicality. One could
argue that we're talking *about* C (which is clearly topical), but
we're using a mixture of Perl and English to discuss it. Think of the
Perl regular expression as a description of how to strip comments from
C source code.


That would make any solution to manipulate C sources implemented in
any language other than C topical in c.l.c. IMHO that would not be a
Good Thing[tm].
On the other hand, not everyone here can be expected to speak Perl
regexps fluently.


Indeed.

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #33

On Sun, 2 Nov 2003, CBFalconer wrote:
Stephen Samuel wrote:
Timex wrote:

I want to delete all comments in .c file.
#!/usr/bin/perl
$s=join("",<>);
# printf "[[%s]]\n\n",$s;
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/[[$1 ]]/g;
printf "[[%s]]\n\n",$s;

/* File uncmntc.c - demo of a text filter
Strips C comments. Tested to strip itself
by C.B. Falconer. 2002-08-15
Public Domain. Attribution appreciated
report bugs to <mailto:cb***** ***@worldnet.at t.net>
*/

<snip code>

I ran your program through some hurdles, and found that
it couldn't handle multibyte character constants for some
reason. I didn't bother to track down why; I just re-wrote
the filter from scratch. ;-) Here's my version, whose
algorithm may be completely different from yours.
This algorithm, on the other hand, completely fails to
handle line-splicing in the middle of comment delimiters: /\
* this is a comment */ does not work, nor does /* this either *\
/. Comment removal really is tricky in the most general case!
Proper error-checking on getc() and putc(), and a good
command-line interface, left as exercises for the interested
reader.
/* File uncmntc2.c - demo of a different text filter
Strips C comments. Tested to strip itself
Improves on CBFalconer's design by correctly handling '/*'
and by having a C89/C99 switch, but doesn't handle the /\
* delimiter correctly.
by Arthur O'Dwyer, 2002-11-03
Public Domain. Attribution appreciated
don't bother reporting bugs, just fix 'em...
*/

#include <stdio.h>
#include <stdlib.h>

/* Strip C99-style end-of-line comments? */
int AllowEOLComment s = 1;

int strip_comments( FILE *fp, FILE *outfp);
static int put_carefully(i nt lastch, int ch, FILE *outfp);
int main(void)
{
strip_comments( stdin, stdout);
return 0;
}
int strip_comments( FILE *fp, FILE *outfp)
{
int ch;
int lastch;
int inchotes = 0;
int inquotes = 0;
int incomment = 0;
int ineolcomment = 0;

for (lastch = ' '; (ch = getc(fp)) != EOF; lastch = ch)
{
if (!incomment && !ineolcomment)
{
if (inquotes || inchotes)
putc(ch, outfp);
else
put_carefully(l astch, ch, outfp);
}

if (inchotes) {
if (ch == '\'' && lastch != '\\')
inchotes = 0;
} else if (inquotes) {
if (ch == '"' && lastch != '\\')
inquotes = 0;
} else if (incomment) {
if (ch == '/' && lastch == '*')
incomment = 0, ch = ' ';
} else if (ineolcomment) {
if (ch == '\n' && lastch != '\\')
ineolcomment = 0;
} else {
if (ch == '\'')
inchotes = 1;
else if (ch == '"')
inquotes = 1;
else if (lastch == '/' && ch == '*') {
putc(' ', outfp);
incomment = 1;
}
else if (AllowEOLCommen ts && lastch == '/' && ch == '/')
ineolcomment = 1;
}
}

if (lastch == '/')
putc(lastch, outfp);

return 0;
}
static int put_carefully(i nt lastch, int ch, FILE *outfp)
{
/* Print out 'ch', but be very careful not to print
* any characters that might be part of a comment
* delimiter. Contrariwise, if 'lastch' is now
* definitely *not* a comment delimiter, we must now
* print it, too.
*/

if (AllowEOLCommen ts) {
if (lastch == '/' && ch == '/')
return 0;
}
if (lastch == '/' && ch == '*')
return 0;
if (lastch == '/')
putc(lastch, outfp);
if (ch != '/')
putc(ch, outfp);
return 0;
}

Nov 13 '05 #34
"Arthur J. O'Dwyer" wrote:
On Sun, 2 Nov 2003, CBFalconer wrote:
.... snip ...
/* File uncmntc.c - demo of a text filter
Strips C comments. Tested to strip itself
by C.B. Falconer. 2002-08-15
Public Domain. Attribution appreciated
report bugs to <mailto:cb***** ***@worldnet.at t.net>
*/ <snip code>

I ran your program through some hurdles, and found that
it couldn't handle multibyte character constants for some
reason. I didn't bother to track down why; I just re-wrote
the filter from scratch. ;-) Here's my version, whose
algorithm may be completely different from yours.

.... snip ...

A known failing. It also fails miserably with trigraphs. The
multibyte char is probably easily handled analogously to handling
quoted strings.

/* File uncmntc2.c - demo of a different text filter
Strips C comments. Tested to strip itself
Improves on CBFalconer's design by correctly handling '/*'
and by having a C89/C99 switch, but doesn't handle the /\
* delimiter correctly.
by Arthur O'Dwyer, 2002-11-03

^^^^
That is the year I wrote mine :-)

All of which shows that there are multiple ways to implement a
black box. I omitted any reference to cats because I happen to
like them.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #35
In <Pi************ *************** ********@unix42 .andrew.cmu.edu > "Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> writes:
[snip] Comment removal really is tricky in the most general case!


Since this is exercise 1-23 in K&R2, there are several solutions
available at Richard's site:

http://users.powernet.co.uk/eton/kandr2/index.html

including a 556-line entry from Chris Torek that I think also brews
coffee...

Pat

BTW, Richard: Would you consider adding a plaintext version of the
"naming conventions" page to the zipfile as a sort of "README"?
Nov 13 '05 #36
Patrick Foley wrote:
BTW, Richard: Would you consider adding a plaintext version of the
"naming conventions" page to the zipfile as a sort of "README"?


I am currently re-evaluating the Answers section of my site. I'll get back
to you when I have a bit more time.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #37
>In <Pi************ *************** ********@unix42 .andrew.cmu.edu > "Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> writes:
[snip] Comment removal really is tricky in the most general case!

In article <nc************ @myname.my.doma in>
Patrick Foley <pf****@earthli nk.net> writes:Since this is exercise 1-23 in K&R2, there are several solutions
available at Richard's site:

http://users.powernet.co.uk/eton/kandr2/index.html

including a 556-line entry from Chris Torek that I think also brews
coffee...


But it has (gasp!) a *bug*. :-) The "level 2 state machine" for
handling comments fails to reconsider characters in a few cases.
I think the main (only?) problem can be fixed without too much
fuss:

case L2_SLASH:
if (c == '*')
l2state = L2_COMM;
else if (c99 && c == '/')
l2state = L2_SLASHSLASH;
else {
SYNCLINES();
OUTPUT('/', 0);
--> if (c != '/') {
--> if (c != EOF)
--> COPY();
--> l2state = L2_NORMAL;
--> }
}
break;

The bug is in the marked lines, which output the first slash
and then change the level-2 state. But the new state should
be "that which results in seeing character c as if the initial
state had been L2_NORMAL", so we could replace all of them with:

l2state = L2_NORMAL;
goto l2_normal_case;

and add an "l2_normal_case " label under case L2_NORMAL: above.
Alternatively, the assignment to l2state can be changed to:

l2state = c == '\'' ? L2_CC :
c == '"' ? L2_SC : L2_NORMAL;

which avoids the dreaded "goto", and simply duplicates what would
have happened in L2_NORMAL state (except of course that instead of
replacing l2state with L2_SLASH for '/', we have to replace it with
L2_NORMAL for characters that are not in [/'"]).
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://67.40.109.61/torek/index.html (for the moment)
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 13 '05 #38
Timex wrote:
I want to delete all comments in .c file.

Size of .c file is very big.

Any good idea to do this?

Please show me example code.


Perhaps a better idea is to break the file into
smaller pieces upon better themes.

I believe that delete all the comments is crime
against programming ethics. After all, one of
the greatest ideals to achieve is to make a
program readable by a programming illiterate
person.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 13 '05 #39
In article <Pi************ *************** ********@unix42 .andrew.cmu.edu >,
Arthur J. O'Dwyer <aj*@nospam.and rew.cmu.edu> wrote:
> Timex wrote:
> >
> > I want to delete all comments in .c file.


I tested Arthur's program and, despite its claim, it couldn't
even strip its own comments (it left in the comment in
put_carefully() ). The bug is that it thought the backslash
meant that '\\' was not a complete character constant (nor
would it think "\\" was a complete string).

Is this a complete C99-style comment?
// \\
If it is, a similar fix may be needed in that part of the code.

Lesson: Comment removal really is tricky in the most general case!

Agreed.

-- Gary

My attempt at a bug fix:
/* File uncmntc2.c - demo of a different text filter
Strips C comments. Tested to strip itself
Improves on CBFalconer's design by correctly handling '/*'
and by having a C89/C99 switch, but doesn't handle the /\
* delimiter correctly.
by Arthur O'Dwyer, 2002-11-03
bug fix by Gary Ansok, 2003-11-06 to handle '\\' and "\\"
Public Domain. Attribution appreciated
don't bother reporting bugs, just fix 'em...
*/

#include <stdio.h>
#include <stdlib.h>

/* Strip C99-style end-of-line comments? */
int AllowEOLComment s = 1;

int strip_comments( FILE *fp, FILE *outfp);
static int put_carefully(i nt lastch, int ch, FILE *outfp);
int main(void)
{
strip_comments( stdin, stdout);
return 0;
}
int strip_comments( FILE *fp, FILE *outfp)
{
int ch;
int lastch;
int inchotes = 0;
int inquotes = 0;
int incomment = 0;
int ineolcomment = 0;
int backslashed = 0;

for (lastch = ' '; (ch = getc(fp)) != EOF; lastch = ch)
{
if (!incomment && !ineolcomment)
{
if (inquotes || inchotes)
putc(ch, outfp);
else
put_carefully(l astch, ch, outfp);
}

if (inchotes) {
if (lastch == '\\')
backslashed ^= 1;
else
backslashed = 0;
if (ch == '\'' && !backslashed)
inchotes = 0;
} else if (inquotes) {
if (lastch == '\\')
backslashed ^= 1;
else
backslashed = 0;
if (ch == '"' && !backslashed)
inquotes = 0;
} else if (incomment) {
if (ch == '/' && lastch == '*')
incomment = 0, ch = ' ';
} else if (ineolcomment) {
if (ch == '\n' && lastch != '\\')
ineolcomment = 0;
} else {
if (ch == '\'')
inchotes = 1;
else if (ch == '"')
inquotes = 1;
else if (lastch == '/' && ch == '*') {
putc(' ', outfp);
incomment = 1;
}
else if (AllowEOLCommen ts && lastch == '/' && ch == '/')
ineolcomment = 1;
}
}

if (lastch == '/')
putc(lastch, outfp);

return 0;
}
static int put_carefully(i nt lastch, int ch, FILE *outfp)
{
/* Print out 'ch', but be very careful not to print
* any characters that might be part of a comment
* delimiter. Contrariwise, if 'lastch' is now
* definitely *not* a comment delimiter, we must now
* print it, too.
*/

if (AllowEOLCommen ts) {
if (lastch == '/' && ch == '/')
return 0;
}
if (lastch == '/' && ch == '*')
return 0;
if (lastch == '/')
putc(lastch, outfp);
if (ch != '/')
putc(ch, outfp);
return 0;
}
Nov 13 '05 #40

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8807
by: Ryan | last post by:
I have a table in my database on SQL Server which holds a file name that refers to a file that is stored on the server. I would like to create a trigger to delete this file from the server if the row in the table is deleted. I have been trying to use this command in a trigger (<filename> is the name and path of the file): xp_cmdshell "delete <filename>" If some one could please help I would appreciate it very much. I would love a...
0
2104
by: SeanR | last post by:
I have a function to copare two files. It will first copy the original file form a different server to a local temp path and then compare that version to a version that has been restored form tape. Once the compare is complete the file that was copied to a temp location needs to be deleted. I am using the method file.copy(sourcePath, tempPath, true) to copy the file and then file.delete(tempPath) to delete the file. On some of the files...
3
1496
by: Huahe | last post by:
I try to delete a file in a for each loop. My code checks if the file exists and if it does, it will delete the file and create a new file with the same name. The first time it works perfect, but the second time it gives me a FileIOException. I want to prevent this from happening. What can i do to make sure the file isn't in use anymore the second time i try to delete it? for each dr in table.rows if file.exist("C:\sample.txt") then...
23
8949
by: da Vinci | last post by:
Greetings, Onwards with the school studying. Working on a program and need to delete a file from a known location on the hard drive but cannot get anything I do to work. I have tried to use the remove function that is included with <cstdio> but cannot get it to work properly. My reference book has the following....
3
2932
by: News | last post by:
Is it possible to delete a file by copying it to the "bit bucket" or "null device"? Back in my youth when I live in VMS-land you could delete a file by copying it to NL: ========== I have written a windows service as part of an interface between two different systems. The first system will write output into a file in a
1
1908
by: Matt Hamilton | last post by:
I have a simple image gallery where I want to allow users to delete files. The problem I have is that after an image is displayed in the browser, I am not able to delete the file because "The process cannot access the file ... It is being used by another process". I also get this error when trying to delete through explorer on the server. I can delete the file if I stop the Web Server service... Is there a way around this? Here is the...
2
4750
by: createdbyx | last post by:
I am trying to make a file sync utillity to sync files between my laptop and my desktop pc. On my desktop machine (xp pro sp2) I have shared my "Visual Studio Projects" folder using windows simple file sharing. And have specified the "Allow network users to change my files." option as well. Then on my laptop (xp home sp2) I have mapped a network drive using windows explorer. So on my laptop I have a Y: drive that points to the "Visual...
0
2851
by: smanisankar | last post by:
hi, the following is the full page code for uploading a file to server. since i got no idea to overwrite the file, i want delete the file if the file is already uploaded. i got the folder name and filename of the file to delete from the request.QueryString("path") so i got the above error when i try to delete the file before upload. Please anyone help me to solve out from this error. <%@ Import Namespace="System.IO" %>
5
1471
by: Neven Klofuar | last post by:
hi, I have a problem when trying to delete a file. I have to extract some information from a file, and then I have to delete it. When I try to delete it after I read it, I get a "Access denied" error. help pls, Neven ********************************
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8973
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.