home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
POINT Software Programming
/
PPROG1.ISO
/
c
/
snippets
/
remcmmnt.c
< prev
next >
Wrap
C/C++ Source or Header
|
1995-03-13
|
5KB
|
146 lines
/*
* REMCMMNT.C
* Remove comments from C or C++ source
*
* ver 1.0, 05 Mar 1995
*
* Public domain by:
* Jari Laaksonen
* Arkkitehdinkatu 30 A 2
* FIN-33720 Tampere
* FINLAND
*
* Fidonet : 2:221/360.20
* Internet: jla@to.icl.fi
*/
#include <stdio.h>
int main (int argc, char **argv)
{
int Char,
Char2,
cpp_comment = 0,
c_comment = 0,
in_string = 0,
cpp_multiline = 0;
char CannotOpen[] = "Cannot open %s\n\n";
FILE *InFile, *OutFile = stdout;
if (argc < 2)
{
fprintf (stderr, "USAGE: REMCMMNT InFile [OutFile]\n");
return 1;
}
if ((InFile = fopen (argv[1], "r")) == NULL)
{
fprintf (stderr, CannotOpen, argv[1]);
return 2;
}
if (argc == 3)
{
if ((OutFile = fopen (argv[2], "w")) == NULL)
{
fprintf (stderr, CannotOpen, argv[2]);
/* if can't open, output goes to stdout instead */
OutFile = stdout;
}
}
while ((Char = fgetc (InFile)) != EOF)
{
if (Char == '\"')
{
Char2 = fgetc (InFile); /* check next char */
if (Char2 != '\'') /* character constant? */
in_string = ! in_string;/* no, toggle flag */
if (c_comment == 0 && cpp_comment == 0)
{
fputc (Char, OutFile);
fputc (Char2, OutFile);
continue;
}
}
if (! in_string)
{
if (Char == '/')
{
Char2 = fgetc (InFile); /* check next char */
if (Char2 == '/') /* start of C++ comment?*/
cpp_comment = 1;
else if (Char2 == '*') /* start of C comment? */
c_comment = 1;
if (c_comment == 0 && cpp_comment == 0)
{
fputc (Char, OutFile);
fputc (Char2, OutFile);
continue;
}
}
else if (Char == '*' && c_comment)
{
Char2 = fgetc (InFile);
if (Char2 == '/') /* end of C comment? */
{
c_comment = 0;
Char = fgetc (InFile);
}
}
if (c_comment || cpp_comment) /* inside C or C++ comment? */
{
/* print newline after comment line is processed */
Char = '\n';
/* rest of the line */
while ((Char2 = fgetc (InFile)) != '\n')
{
if (Char2 == '\\' && cpp_comment)
cpp_multiline = 1;
if (Char2 == '*' && c_comment)
{
Char2 = fgetc (InFile); /* check next */
if (Char2 == '/') /* end C comment? */
{
c_comment = 0;
Char = fgetc (InFile);
break;
}
/* single splat inside C comment */
if (Char2 == '\n')
break;
}
}
if (cpp_comment && cpp_multiline == 0)
cpp_comment = 0;
if (c_comment || cpp_comment)
fputc (Char, OutFile);
/*
** clear flag for the next round. if it is still
** clear after next C++ comment line is processed,
** multiline C++ comment is ended.
*/
cpp_multiline = 0;
}
}
if (c_comment == 0 && cpp_comment == 0)
fputc (Char, OutFile);
} /* while end */
if (argc == 3)
fclose (OutFile);
fclose (InFile);
fflush (stdout);
fprintf (stderr, "\nOK!\n");
return 0;
}