Here is the portion of my C program:
FILE *fin_length;
int c;
int countNewLines = 0;
fin_length = fopen( argv[1], "r" );
while( ( c == fgetc( fin_length ) ) != EOF ) {
if( c == 10 ) countNewLines++;
}
fclose( fin_length );
I run the program with command line arguments ./a.out myMessage.dat. myMessage.dat is 5 lines long, where each line contains nothing more than a short sentence. Therefore, I expect the loop to find these 5 lines with if( c == 10 ) and add one to countNewLines every time it finds a carriage return.
Why am I getting an infinite loop here?
while( ( c == fgetc( fin_length ) ) != EOF ) {You have too many equal signs. This should be
while( ( c = fgetc( fin_length ) ) != EOF ) {When you use
==, you end up with two comparisons. The first is a comparison betweencand the return value offgetc().The second comparison compares that result (which is either
trueorfalse) withEOF. I have not looked up the value ofEOF, but it is certainly not0or1– meaning that the second comparison will never return false.