How do you write a C program which reads a C source file and creates a copy of that file with all comments removed?
#include<stdio.h>
void strip_comments (FILE* input, FILE* output) {
enum enum_mode {normal, slash, q1, q1b, q2, q2b, single, multi,
star};
int ichar;
enum_mode mode;
mode = normal;
while ((ichar=fgetc(input))!=EOF) {
switch (mode) {
case normal:
switch (ichar) {
case '/':
mode=slash;
break;
case '\'':
fputc (ichar, output);
mode=q1;
break;
case '"':
fputc (ichar, output);
mode=q2;
break;
default:
fputc (ichar, output);
}
break;
case slash:
switch (ichar) {
case '/':
mode=single;
break;
case '*':
mode=multi;
break;
default:
fputc ('/', output);
fputc (ichar, output);
mode=normal;
}
break;
case q1:
switch (ichar) {
case '\\':
fputc ('\\', output);
mode=q1b;
break;
case '\'':
fputc (ichar, output);
mode=normal;
break;
default:
fputc (ichar, output);
}
break;
case q1b:
fputc (ichar, output);
mode=q1;
break;
case q2:
switch (ichar) {
case '\\':
fputc (ichar, output);
mode=q2b;
break;
case '"':
fputc (ichar, output);
mode=normal;
break;
default:
fputc (ichar, output);
}
break;
case q2b:
fputc (ichar, output);
mode=q2;
break;
case single:
switch (ichar) {
case '\r':
case '\n':
fputc (ichar, output);
mode=normal;
break;
}
break;
case multi:
switch (ichar) {
case '*':
mode=star;
break;
}
break;
case star:
switch (ichar) {
case '/':
mode=normal;
break;
default:
mode=multi;
}
break;
}
}
}
int main (int argc, char* argv[]) {
if (argc!=3) {
char* prog;
prog=argv[0];
while (*prog!=0) ++prog;
while (*prog!='.') { *prog=0; --prog; }
*prog=0;
while (*prog!='\\') --prog;
++prog;
fprintf(stderr, "Comment stripper for C/C++ source
files\n");
fprintf(stderr, "Copyright © 2016, PCForrest\n\n");
fprintf(stderr, "Usage:\n\n%s src dst\n\n", prog);
fprintf(stderr, " src - source file\n");
fprintf(stderr, " dst - destination file\n\n");
return -1;
}
FILE* source;
FILE* destination;
source=fopen(argv[1], "r");
destination=fopen(argv[2], "w");
if (!source !destination) {
if (source)
fclose (source);
if (destination)
fclose (destination);
return -1;
}
strip_comments (source, destination);
fclose (source);
fclose (destination);
return 0;
}