On another question, Jerry Coffin pointed out the following:
It's (probably) not really related to your question, but
while (!feof(fileptr)){
is pretty much a guaranteed bug.
I figured I would start a separate question since that comment is somewhat off-topic. Could someone explain this to me? This was the first program I've written in straight C before.
The C FAQ list has an answer along with answers to many other such frequently asked questions:
Google finds this: http://www.drpaulcarter.com/cs/common-c-errors.php#4.2
It says "The author has yet to see any student use the feof() function correctly!"
To summarize, the C file functions like
fread
andfwrite
return status values anyway which you <blink>should not ignore</blink>. Checking the value offeof
is one of those bolting the stable door after the horse has already fled kind of things.The reason for this statement is that
feof
is still (initially) false when the end of the file has been reached -- it only becomes true after the first failed attempt to read past the end of the file.Hence
will process one char too many.
The correct way is to check the return value of
fread
(or whatever function you're using to read) or, alternatively, to callfeof
after the function that does the reading. For example: