-
Printing a file
I had written the following code which does the following:
It takes in a series of integers as input.
It prints all the integers that come before 42 has been input (assumes that the user inputs 42 at some point of time) to the screen as well as to a file named out.txt.
The printing to the screen is done by reading from the out.txt file.
While printing to the screen, I found that the last integer was being printed twice (on screen) even though the output of the text file is correct. Why is this ?
Code:
#include <stdio.h>
int main()
{
FILE *fp1;
fp1 = fopen("out.txt", "w");
int n,i;
do
{
scanf("%d", &n);
if(n == 42)
break;
fprintf(fp1, "%d\n", n);
}while(n!=42);
fclose(fp1);
fp1 = fopen("out.txt", "r");
while(!feof(fp1))
{
fscanf(fp1, "%d", &n);
printf("%d\n", n);
}
fclose(fp1);
getch();
return 0;
}
-
That's the unfortunate way that feof() works. It's weird. I wouldn't use it. Use the return from fscanf(), instead. If it's greater than zero, it's still getting data.
-
So, modifying this part will work ?
Code:
while(fscanf(fp1, "%d", &n) > 0)
printf("%d\n", n);
How does feof work exactly ?
-
This explains it better than I can:
http://www.gidnetwork.com/b-58.html
I just a little (double) test of feof(), and OF COURSE, it worked just fine without any double checking. Go figure! :p :p :p
C'est la vie!