Reputation: 65
I'm learning about file i/o in C language and I wrote this program that reads a file, and then for every even number found, it has to print *
to the screen.
My problem is that my program keeps printing *
forever.
I have tried different ways,some from this website, but I can't seem to understand how to read until end of a text file using EOF.
I want to learn how to read a text file until the end of the file please. How do I read until the end of a text file? EOF in C.
int main(void)
{
int num;
FILE *ifp;
ifp = fopen("numbers.txt", "r" );
if(ifp == NULL)
{
exit(1);
}
do
{
fscanf(ifp, "%d", &num);
if(num%2 == 0)
{
printf("*\n");
}
} while(num != EOF);
fclose(ifp);
return 0;
}
Upvotes: 1
Views: 435
Reputation: 71
It's doing this because while(num != EOF)
is testing whether int num
, the number read from the file, is EOF
, rather than whether the end of file has been reached.
To test whether the EOF flag has been set on FILE *ifp
, use while(!feof(ifp))
instead.
Upvotes: 0
Reputation: 401
Have you tried this:
while (!feof(ifp)) {
if (fscanf(ifp, "%d ", &num) > 0) {
if(num % 2 != 0) // For every odd number.
{
printf("*\n");
}
}
}
Upvotes: 0
Reputation: 1153
Instead, you should try while
loop.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num;
FILE *ifp;
ifp = fopen("numbers.txt", "r" );
if(ifp == NULL)
{
perror("Read");
exit(1);
}
while(fscanf(ifp, "%d ", &num) != EOF)
{
if(num % 2 != 0) // For every odd number.
{
printf("*\n");
}
}
fclose(ifp);
return 0;
}
Upvotes: 0
Reputation: 67546
you need to check the result of the scanf
do
{
int result;
result = fscanf(ifp, "%d", &num);
if(result == EOF) break;
if(result != 1)
{
printf("scanf error\n");
break;
}
if(num%2 == 0)
{
printf("*\n");
}
} while(1);
Upvotes: 2