473,785 Members | 3,032 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
*** rude top-posting fixed ***

Stephen Samuel wrote:
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.


Here's a perl script which will handle *MOST* sane C code...

Some things that it will miss (scan manually for it first:

a double quote inside of single quotes (e.g.)
char confusion = '"';

C-99 // comments like this

I'm sure that some people can come up with other convoluted
counter-examples.

It reads and plays with the entire file, so it will need to
hold at least two or three copies of it in RAM. (for today's
computers, that would be some number of megabytes).

If you want any of the above fixed, feel free to send me a
cheque.
_______________ _______________ _______________ _______
#!/usr/bin/perl
$s=join("",<>);
# printf "[[%s]]\n\n",$s;
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/[[$1 ]]/g;
printf "[[%s]]\n\n",$s;
_______________ _______________ _______________ _______
Yep, That's it... 5 lines including the shell header.


Please do not top-post.

The following AFAIK does not have the above faults, and does not
need to store any file copies, in fact not even any line copies.
It will probably be at least an order of magnitude faster.

/* 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>
*/

/* With gcc3.1, must omit -ansi to compile eol comments */

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

static int ch, lastch;

/* ---------------- */

static void putlast(void)
{
if (0 != lastch) fputc(lastch, stdout);
lastch = ch;
ch = 0;
} /* putlast */

/* ---------------- */

/* gobble chars until star slash appears */
static int stdcomment(void )
{
int ch, lastch;

ch = 0;
do {
lastch = ch;
if (EOF == (ch = fgetc(stdin))) return EOF;
} while (!(('*' == lastch) && ('/' == ch)));
return ch;
} /* stdcomment */

/* ---------------- */

/* gobble chars until EOLine or EOF. i.e. // comments */
static int eolcomment(void )
{
int ch, lastch;

ch = '\0';
do {
lastch = ch;
if (EOF == (ch = fgetc(stdin))) return EOF;
} while (!(('\n' == ch) && ('\\' != lastch)));
return ch;
} /* eolcomment */

/* ---------------- */

/* echo chars until '"' or EOF */
static int echostring(void )
{
putlast();
if (EOF == (ch = fgetc(stdin))) return EOF;
do {
putlast();
if (EOF == (ch = fgetc(stdin))) return EOF;
} while (!(('"' == ch) && ('\\' != lastch)));
return ch;
} /* echostring */

/* ---------------- */

int main(void)
{
lastch = '\0';
while (EOF != (ch = fgetc(stdin))) {
if ('/' == lastch)
if (ch == '*') {
lastch = '\0';
if (EOF == stdcomment()) break;
ch = ' ';
putlast();
}
else if (ch == '/') {
lastch = '\0';
if (EOF == eolcomment()) break;
ch = '\n';
putlast(); // Eolcomment here
// Eolcomment line \
with continuation line.
}
else {
putlast();
}
else if (('"' == ch) && ('\\' != lastch)
&& ('\'' != lastch)) {
if ('"' != (ch = echostring())) {
fputs("\"Unterm inated\" string\n", stderr);
fputs("checking for\
continuation line string\n", stderr);
fputs("checking for" "concat string\n", stderr);
return EXIT_FAILURE;
}
putlast();
}
else {
putlast();
}
} /* while */
putlast(/* embedded comment */);
return 0;
} /* main */
--
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 #21


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.


Try "ncsl": http://www.lucentssg.com/displayProduct.cfm?prodid=33
It strips all comments and indentation so just run an indenter (e.g.
"indent") or a C beautifier (e.g. "cb" - google for "cb download
beautifier" and take your pick) on the output to get it back in readable
format. Disclaimer - I've never used this specific download of "ncsl",
I've just used the version provided on UNIX boxes within Lucent.

Ed.

Nov 13 '05 #22
Here's a perl script which will handle *MOST* sane C code...

Some things that it will miss (scan manually for it first:

a double quote inside of single quotes (e.g.)
char confusion = '"';

C-99 // comments like this

I'm sure that some people can come up with other convoluted counter-examples.

It reads and plays with the entire file, so it will need to hold
at least two or three copies of it in RAM. (for today's computers,
that would be some number of megabytes).

If you want any of the above fixed, feel free to send me a cheque.
_______________ _______________ _______________ _______
#!/usr/bin/perl
$s=join("",<>);
# printf "[[%s]]\n\n",$s;
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/[[$1 ]]/g;
printf "[[%s]]\n\n",$s;
_______________ _______________ _______________ _______
Yep, That's it... 5 lines including the shell header.

One bug: Quoted strings have a space inserted after them.
Again: fixable, but not worth the trouble for free.

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.

--
Stephen Samuel +1(604)876-0426 sa****@bcgreen. com
http://www.bcgreen.com/~samuel/
Powerful committed communication. Transformation touching
the jewel within each person and bringing it to light.
Nov 13 '05 #23
Here's a perl script which will handle *MOST* sane C code...

Some things that it will miss (scan manually for it first:

a double quote inside of single quotes (e.g.)
char confusion = '"';

C-99 // comments like this

I'm sure that some people can come up with other convoluted counter-examples.

It reads and plays with the entire file, so it will need to hold
at least two or three copies of it in RAM. (for today's computers,
that would be some number of megabytes).

If you want any of the above fixed, feel free to send me a cheque.
_______________ _______________ _______________ _______
#!/usr/bin/perl
$s=join("",<>);
# printf "[[%s]]\n\n",$s;
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/[[$1 ]]/g;
printf "[[%s]]\n\n",$s;
_______________ _______________ _______________ _______
Yep, That's it... 5 lines including the shell header.

One bug: Quoted strings have a space inserted after them.
Again: fixable, but not worth the trouble for free.

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.

--
Stephen Samuel +1(604)876-0426 sa****@bcgreen. com
http://www.bcgreen.com/~samuel/
Powerful committed communication. Transformation touching
the jewel within each person and bringing it to light.
Nov 13 '05 #24
Irrwahn Grausewitz wrote:
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?

It's a C solution .. But Perl is written in C, so if you like,
I can just
#include <perl-source.c>
BTW:
Does your "solution" account for comment delimiters inside string
literals? (I'm unfortunately unable to decrypt the line-noise
provided.)


Yes. It accounts for comment delimiters in quotes and quote
delimiters in comments (One side effect is that double quote
strings have a space added after them. Given the way that I
wrote it, it was a choice between that, replacing comments with
Nothing (possible to cause syntax errors) or added complexity.)

It also handles quoted double-quotes inside of strings.

It does NOT handle double-quote or comment-start delimiters inside
of single-quotes (char literals), but that would be easy enough to add.
--
Stephen Samuel +1(604)876-0426 sa****@bcgreen. com
http://www.bcgreen.com/~samuel/
Powerful committed communication. Transformation touching
the jewel within each person and bringing it to light.
Nov 13 '05 #25
Stephen Samuel <st************ @telus.net> scribbled the following:
Irrwahn Grausewitz wrote:
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?

It's a C solution .. But Perl is written in C, so if you like,
I can just
#include <perl-source.c>


Are Perl implementations *required* to be written in C? And are
Perl implementations *required* to ship with the source code?

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"'So called' means: 'There is a long explanation for this, but I have no
time to explain it here.'"
- JIPsoft
Nov 13 '05 #26
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).

Appologies. I'm an old foggie, and it's probably been an decade
since I've posted here.

--
Stephen Samuel +1(604)876-0426 sa****@bcgreen. com
http://www.bcgreen.com/~samuel/
Powerful committed communication. Transformation touching
the jewel within each person and bringing it to light.
Nov 13 '05 #27
"Stephen Samuel" wrote:
Irrwahn Grausewitz wrote:
Since when is perl topical in c.l.c? It's a C solution


Err, no.
.. But Perl is written in C, so if you like,
I can just
#include <perl-source.c>
Non-standard header file. ;-)
Does your "solution" account for comment delimiters inside string
literals?


Yes.


Nice.
It accounts for comment delimiters in quotes and quote
delimiters in comments (One side effect is that double quote
strings have a space added after them. Given the way that I
wrote it, it was a choice between that, replacing comments with
Nothing (possible to cause syntax errors) or added complexity.)
Hm. AFAICT that shouldn't cause much trouble, OK.
It also handles quoted double-quotes inside of strings.
ITYM something like "\""?
It does NOT handle double-quote or comment-start delimiters inside
of single-quotes (char literals), but that would be easy enough to
add.


Fair enough.
But still there might be "strange" cases caused where your script may
fail. Consider:

/* gotcha! *\
/

A C preprocessor would have deleted the <backslash><n ew-line> sequence
in translation phase 2 *before* the tokenization and comment replacement
takes place in phase 3. And if the backslash is written as a trigraph
sequence we need to "fake" translation phase 1 as well... :-(

Admittedly, these are rare situations, but you see: sophisticated
comment replacement in C files isn't /that/ easy after all, you have to
provide quite an amount of preprocessor functionality to get it right.

Best Regards
--
Irrwahn

PS: Please don't email me if you already posted
your reply to the newsgroup; thank you.
Nov 13 '05 #28
Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
[...]
Are Perl implementations *required* to be written in C? And are
Perl implementations *required* to ship with the source code?


<OT>
Perl is pretty much defined by its implementation, not by a language
standard. The implementation (there's basically only one) is written
in C. It's distributed under one of two open source licenses, both of
which require the source to be available (but not necessarily shipped
with the binaries).

This is probably incorrect in some minor details. If I had posted to
a more appropriate newsgroup, someone would jump in and correct me.
</OT>

--
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 #29
Keith Thompson <ks*@cts.com> scribbled the following:
Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
[...]
Are Perl implementations *required* to be written in C? And are
Perl implementations *required* to ship with the source code?
<OT>
Perl is pretty much defined by its implementation, not by a language
standard. The implementation (there's basically only one) is written
in C. It's distributed under one of two open source licenses, both of
which require the source to be available (but not necessarily shipped
with the binaries). This is probably incorrect in some minor details. If I had posted to
a more appropriate newsgroup, someone would jump in and correct me.
</OT>


OK, I have to concede with that, but Samuel's answer still wasn't
sufficient. Writing #include <perl_source. h> at the top of the Perl
file will change the program into a mix-and-match of C and Perl,
which will not compile as either language.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Roses are red, violets are blue, I'm a schitzophrenic and so am I."
- Bob Wiley
Nov 13 '05 #30

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...
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...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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.