Archived

This topic is now archived and is closed to further replies.

dvogel

File handles

Recommended Posts

Something peculiar is happening with this code: ------------------------------------------------------------ fp = fopen(path, "r"); if (fp == NULL) fatal(ESTR_FOPEN); units_read = fread(&image_width, sizeof(image_width), 1, fp); ------------------------------------------------------------ After the call to fopen(), both feof() and ferror() return 0. The call to fread() returns 0, but after the call returns, a subsequent call to feof() returns 1 and ferror() still returns 0. How can we go from something not the end of the file to the end of the file without reading anything? Does anyone know why this is or could be happening? Regards, Drew Vogel

Share this post


Link to post
Share on other sites
Why don''t you explain a bit more on what you''re actually trying to accomplish, and we can help you out with the "proper" code?

FILE *fp;
fp = fopen(path,"rb"); //Read BINARY!
if (fp == NULL)
fatal(ESTR_FOPEN);

units_read = fread(&image_width, sizeof(image_width),1,fp);

Instead of opening it for "r", open it for "rb", othrewise, you are trying to do a binary read on a file that was opened for text reading (I beleive the default is text, don''t hold me to that though).

Share this post


Link to post
Share on other sites
You need to remember that eof is not set until you actually attempt to read past the end of file. In other words, even if the file is completely empty eof will not be set until you try to read something.

-Neophyte

Share this post


Link to post
Share on other sites
Thank you for that tidbit of info Neophyte. That explains how the situation is possible. Back to debugging...

As to the other two posts, fp is set to NULL when it is declared. That is irrelevant in this discussion. Furthermore, you don''t need to know the purpose of the code as it has nothing to do with the problem described. If you can''t see why, stop posting. Also, my operating system doesn''t specify between text and binary files. I''m sorry yours does.


Regards,
Drew Vogel

Share this post


Link to post
Share on other sites
quote:
Original post by dvogel
units_read = fread(&image_width, sizeof(image_width), 1, fp);



What kind of variable is image_width? Have you allocated a sufficient amount of memory for it?

Regarding the confusion over the subseqent eof, my docs on fread say that if an error occurs, the resulting value of the file position indicator for the stream is indeterminate.

Share this post


Link to post
Share on other sites