John Doe
John Doe

Reputation: 95

Need help resolving weird fscanf issue

I am trying to read from a file line by line by running it through a while loop which is instructed to exit once EOF has been reached. But for some reason once the last line has been read and the while condition is checked again the program just freezes.

This is my code:

char character1;
int number1;

while(fscanf(file,"%s %d",&character1, &number1) != EOF){
    //printf("%s %d\n",character1,number1) 
}

My files contents:

A 1
B 2
C 3
D 4
E 5

Output:

A 1
B 2
C 3
D 4
E 5
|    <---Blinking terminal pointer currently there

Can anyone help me figure this out?

EDIT: I am not opening/closing the file in main(), I am doing it in another function, could this be causing a problem?

Upvotes: 1

Views: 76

Answers (2)

T Johnson
T Johnson

Reputation: 824

Improve the condition checking on the while loop. The fscanf() can produce more results that EOF or a positive number. It can also return a positive number when an end-of-file occurs after conversion has begun. Meaning that you have something going wrong with a conversion and so the data is still there the next time you loop around to get more data from the stream. So you are stuck infinitely failing to convert that same failed conversion.

You are looking for 2 input items so check that the fscanf() has found 2 input items in order to continue looping.

Upvotes: 1

lucasmonteiro001
lucasmonteiro001

Reputation: 83

The problem is that your fscanf reads the \r or \n in the end of every line. Just creates a buffer to ignore it and will be fine. I did the following and it worked smoothly.

char character1;
int number1;
char buffer[2]; // will read the end of line

while(fscanf(file,"%c %d",&character1, &number1) != EOF){
    fgets(buffer, 2, file);// does the job
    printf("[%c] [%d]\n",character1,number1);
}

Upvotes: 0

Related Questions