1

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;
}

Kakarotto
  • 65
  • 7

4 Answers4

2

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);
0___________
  • 60,014
  • 4
  • 34
  • 74
  • hey! thx, I made those changes, and now is not printing `*`. I checked with he debugger and noticed that goes into the `scanf error` in line 25 – Kakarotto Jun 05 '20 at 06:34
  • 2
    so you have the problem with your file. It fails to scan. ***Always*** check the result of any I/O operation – 0___________ Jun 05 '20 at 06:35
0

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.

0

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;
}
Shubham
  • 1,153
  • 8
  • 20
0

Have you tried this:

while (!feof(ifp)) {
   if (fscanf(ifp, "%d ", &num) > 0) {
      if(num % 2 != 0) // For every odd number.
                {
                printf("*\n");
                }
   }
}
Catch22
  • 391
  • 2
  • 5