Reputation:
I am currently getting myself into fileusage in C. I found a code explaining reading strings from a file. However I am really curious how this mechanically works.
while (!feof(fPointer)){
fgets(singleLine, 150, fPointer);
puts(singleLine);
}
How does the filepointer know at the end of the loop to go for a further line? Shouldnt the filepointer be increased at the end of the while loop?
Cheers
Upvotes: 0
Views: 360
Reputation: 85887
A FILE
object stores information about an open file, including a "current positition". Each read/write operation increments the current position by how many bytes were read/written. That's why you can just keep calling fgets
(or any other input function) in a loop and get the contents, chunk by chunk.
Similarly, you can just call printf
(or any other output function) multiple times to produce output, and they won't overwrite each other.
You can get and set the current file position using ftell
and fseek
(subject to some restrictions, e.g. standard C doesn't require ftell
to return an actual byte offset on text files, just some "magic number" that can be passed to fseek
(but I've never seen that in a real implementation)).
(Your fPointer
just points to one FILE
object. You shouldn't increment this pointer; it'll just point to random memory.)
Finally, while (!feof(fp))
is wrong because feof
queries the "end of file" bit stored in the FILE
object. It does not predict whether the next read will fail due to reaching the end of the file. The "end of file" bit is only set to true after an input function reaches the end of the file. This kind of loop will run once more after end-of-file and then process garbage (or stale, from the previous iteration) data.
Upvotes: 3