[ fscanf reads a line that does not exists in a file ]
I'm on a Fedora 15 computer and I have a simple code that looks like this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x[50], y[50];
int i;
FILE *f_in = fopen("readtest.dat","r");
if (f_in == NULL) printf("No file...\n");
else
{
i = 0;
while (!feof(f_in))
{
fscanf(f_in,"%d %d",&x[i],&y[i]);
printf("%d %d\n", x[i], y[i]);
i++;
}
printf("I've read %d data.\n", i);
}
return 0;
}
The file to be read is this
1 1
2 2
3 3
4 4
5 5
But I don't know why the output looks like this.
1 1
2 2
3 3
4 4
5 5
1250259108 1250140145
I've read 6 data.
I was thinking that I left a blank new line in the file, but I didn't. I double checked the file with both gedit and vim and no blank lines were found. Why am I reading this unexisting line?
Answer 1
Probably last call to fscanf
functions failed.
These functions return the number of input items assigned. This can be fewer than provided for, or even zero, in the event of a matching failure.
Check its return value before printing. Something like:
v = fscanf(f_in,"%d %d",&x[i],&y[i]);
if (v) {
// printf goes here
}
Answer 2
As user786653 said (by reference, at least) in his comment, "while !feof" is the wrong way to read a file in C. feof doesn't return true until you've hit the end of the file, and actually tried to read past it. So your program does an extra read, which fails.
Answer 3
You should include a new line escape character in your fscanf
fscanf(f_in,"%d %d\n",&x[i],&y[i]);
Also dont forget to fclose
your file
EDIT
I tried it and here are the results.
Without the \n
1 1
2 2
3 3
4 4
5 5
-1216418984 1
I've read 6 data.
With the \n
1 1
2 2
3 3
4 4
5 5
I've read 5 data.