File handles

Started by
4 comments, last by dvogel 21 years, 1 month ago
Something peculiar is happening with this code: ------------------------------------------------------------ fp = fopen(path, "r"); if (fp == NULL) fatal(ESTR_FOPEN); units_read = fread(ℑ_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
Regards,Drew Vogel
Advertisement
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(ℑ_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).
Yes, the default is text....

You should also init your fp to NULL, just to be safe.

FILE *fp = NULL;
"I once thought I was wrong, but then I was mistaken." - A4
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
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
Regards,Drew Vogel
quote:Original post by dvogel
units_read = fread(ℑ_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.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man

This topic is closed to new replies.

Advertisement