/* The C Programming Language
my solution for exercise 1-23
Parse a .c file and remove all comments */
#include <stdio.h>
#include <string.h>
#define MAXFILENAME 256
int main(int argc, char* argv[])
{
char in_name[MAXFILENAME];
char out_name[MAXFILENAME];
char buf, oneAhead;
int openSlash, openStar, closeStar, closeSlash, inComment;
FILE *fp_in, *fp_out;
openSlash = openStar = closeStar = closeSlash = inComment = 0;
if (argc != 3){
printf("remove_comments usage:\n\tremove comments [input filename] [output filename]");
return 1;
}
if( strcmp(argv[1],argv[2]) == 0 ){
printf("remove_comments error:\n\tinput and output file names must be different");
return 2;
}
strcpy(in_name, argv[1]);
strcpy(out_name, argv[2]);
/* Attempt to open our files for reading / writing */
fp_in = fopen(in_name, "r");
fp_out = fopen(out_name, "w");
if( fp_in == NULL ){
printf("remove_comments error:\n\tcould not open %s for reading.", in_name);
return 3;
}
if( fp_out == NULL ){
printf("remove_comments error:\n\tcould not open %s for writing.", out_name);
return 4;
}
/* Read a .c file char by char, if we're in a comment don't copy */
while ((buf = fgetc(fp_in)) != EOF)
if ( inComment == 0 )
if ( buf == '/' && (oneAhead = fgetc(fp_in)) == '*' )
inComment = 1;
else
fputc(buf, fp_out);
else if ( inComment == 1 )
if ( buf == '*' && (oneAhead = fgetc(fp_in)) == '/' )
inComment = 0;
fclose(fp_in);
fclose(fp_out);
return 0;
}