I have a text file that has strings on each line. I want to increment a number for each line in the text file, but when it reaches the end of the file it obviously needs to stop. I’ve tried doing some research on EOF, but couldn’t really understand how to use it properly.
I’m assuming I need a while loop, but I’m not sure how to do it.
How you detect EOF depends on what you’re using to read the stream:
Check the result of the input call for the appropriate condition above, then call
feof()to determine if the result was due to hitting EOF or some other error.Using
fgets():Using
fscanf():Using
fgetc():Using
fread():Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You’ll see a lot of examples like:
This form doesn’t work the way people think it does, because
feof()won’t return true until after you’ve attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.