Reputation: 10698
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?
Upvotes: 2
Views: 285
Reputation: 1053
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 between c
and the return value of fgetc()
.
The second comparison compares that result (which is either true
or false
) with EOF
. I have not looked up the value of EOF
, but it is certainly not 0
or 1
- meaning that the second comparison will never return false.
Upvotes: 5
Reputation: 375584
Because you used ==
in your while, you want this:
while ((c = fgetc(fin_length)) != EOF) {
You were getting a boolean from ==
then comparing that against EOF
, and it was never equal, so your loop was infinite.
Upvotes: 4
Reputation:
Because ==
(equality) is not the same as =
(assignment).
Happy coding.
Upvotes: 2