I've started studying C in the university. The professor gave us a task - to write a program that counts the number of comments in an another C program. We still haven't talked about operating with files. I found a similar solution - C Program to count comment lines (// and /* */) . Modified it a bit and it actually works but I can't understand the enum
stuff. Tried to rewrite it without enumerations but with no success (cuz we have to explain how to program works). My question is - is there a way to solve it without enumerations?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fp;
int c, i=0;
char ch;
char path[150];
unsigned int chars = 0;
unsigned int multi = 0;
unsigned int single = 0;
enum states { TEXT,
SAW_SLASH,
SAW_STAR,
SINGLE_COMMENT,
MULTI_COMMENT } state = TEXT;
printf("Write file's path. Separate the folders with TWO back slashes (\\)\n");
scanf("%s", &path);
fp = fopen(path, "r");
if ( !fp )
{
fprintf(stderr, "Cannot open file %s\n", argv[1] );
}
else {
while((c=fgetc(fp)) != EOF){
switch( state ) {
case TEXT :
switch( c )
{
case '/' : state = SAW_SLASH; break;
default : break;
}
break;
case SAW_SLASH :
switch( c )
{
case '/' :
printf("case SLASH case / \n");
state = SINGLE_COMMENT;
break;
case '*' :
printf("case SLASH case * \n");
state = MULTI_COMMENT;
break;
default :
state = TEXT;
break;
}
break;
case SAW_STAR :
switch( c )
{
case '/' :
printf("case STAR case / \n");
state = TEXT;
multi++;
break;
case '*' :
break;
case '\n' :
printf("case SLASH case 'NEW LINE' \n");
multi++; // fall through
default :
state = MULTI_COMMENT;
break;
}
break;
case SINGLE_COMMENT :
switch( c )
{
case '\n' :
printf("case SINGLE case NEW LINE \n");
state = TEXT;
single++; // fall through
default :
break;
}
break;
case MULTI_COMMENT :
switch( c )
{
case '*' :
printf("case MULTI case * \n");
state = SAW_STAR;
break;
case '\n' :
break;
default :
break;
}
break;
default: // NOT REACHABLE
break;
}
}
fclose(fp);
printf( "File : %s\n", argv[1] );
printf( "Single-comment: %8u\n", single );
printf( "Multi-comment: %8u\n", multi );
}
return 0;
}