16

I am reading from file of format

1 32 43 23
32 43
123 43 54 243 
123 2222
2

Here is my code snippet.

string[100];
while(!feof(fp))
    fgets(string,100,fp)

Now, when I put every string, in the last string I am getting repetition and some more ambiguities (like something else also gets printed say 123 or so).

How to solve this problem?

2
  • Is there an end-of-line \n character at the end of the last line in your file? Feb 24, 2012 at 16:21
  • 2
    Post your full actual code, this shouldn't even compile.
    – Staven
    Feb 24, 2012 at 16:22

2 Answers 2

27

You need to check the return value of fgets. If a read has been successful, fgets returns the pointer to the buffer that you passed to it (i.e. string in your example). If the End-of-File is encountered and no characters have been read, fgets returns NULL.

Try this:

char string[100];
while(fgets(string, 100, fp)) {
    printf("%s\n", string);
}
5
  • 1
    Why would you test with feof if fgets does so? Jan 25, 2015 at 23:00
  • 2
    @ManuelReis You are right, feof test s unnecessary (edited). Jan 25, 2015 at 23:05
  • 4
    Thanks for the answer, I was having an existential crisis for a second. Jan 25, 2015 at 23:07
  • 2
    The \n inside issued by the printf is not necessary, as it already comes via fgets() from inside the file (if around).
    – alk
    Nov 8, 2016 at 9:36
  • Having fgets() return value assumed to be 0, this code works. Generally NULL is not necessarily 0, it is generally (void*)0. Code is more readable, if you check with NULL Jan 1, 2017 at 23:53
7

The eof is only reached after you have attempted to read from a file that is at the end. You have to use the return value of fgets instead (which returns NULL on eof or error and the pointer it is given otherwise):

char string[100];
while(fgets(string, 100, fp))
    // do stuff with string

Checking the return value like this will cause you never to hit the eof inside the body of the loop, like the other one, instead of in the condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.