PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to use EOF to read all data from file

 October 30, 2022     c, eof, file-io     No comments   

Issue

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


Solution

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


Answered By - 0___________
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing