Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this generate an Infinite Loop?

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?

like image 554
Mxyk Avatar asked Dec 05 '25 10:12

Mxyk


2 Answers

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.

like image 142
Mark Avatar answered Dec 07 '25 22:12

Mark


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.

like image 34
Ned Batchelder Avatar answered Dec 08 '25 00:12

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!