Question: How can I only count the lines of code in a source file and ignore the comment lines and blank lines?
For example, if I have a source file as follows how would I only count the lines as described above.
Thanks!
Flight
Code:#include <stdio.h> #include <stdlib.h> int main() { //declarations char file_name[100], line1[10] ; FILE *inp1, *out1 ; int count, update_counter ; // init some stuf count=0 ; update_counter = 0 ; // prompt the user printf("Enter Filename : ") ; // read the keyboard input fgets(file_name, sizeof(file_name), stdin); //remove the newline character from the end of the filename file_name[strlen(file_name) - 1] = '\0' ; // open input file inp1 = fopen(file_name, "r") ; if(inp1 == NULL) { fprintf(stderr, "can't open %s\n", file_name) ; exit(EXIT_FAILURE) ; } // open output file #1 out1 = fopen("output1.txt", "w") ; if(out1 == NULL) { fprintf(stderr, "can't open %s\n", "output1.txt") ; exit(EXIT_FAILURE) ; } // count the words in the input file for ( ;; ) { int ch = fgetc(inp1); if ( ch == EOF ) { break; } if ( isalnum(ch) || ispunct(ch)) { update_counter = 1; } else if ( isspace(ch) && update_counter ) { count++ ; update_counter = 0; } } //for those files that end with lines with no line feeds //this will increment the counter one last time... if (update_counter) { count++; } //write the word count to the output file fprintf(out1,"File %s contains %d words \n", file_name, count) ; // we're done...close files fclose(inp1) ; fclose(out1) ; return 0; }



LinkBack URL
About LinkBacks




