开发者

problem with fread

i am trying to read one byte at a time from a file:

size_t result_new = 1;  
char buf6[1];  
if( (result_new = fread(buf6, 1, 1, pFile)) != 1)  
            {  
                printf("result_new = %d\n", result_new);
                printf("Error reading file\n");
                exit(1);
            }

result_new is becoming 0 and it is printing the err开发者_StackOverflowor. any idea what can be wrong. im sure pFile is fine.

thanks


According to the documentation:

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

So why don't you check error code that will answer your question? You can use perror, for example.


If you only need one byte, getc would be a much better choice than fread. The interface is simpler and it's likely to be a lot faster.


http://www.cplusplus.com/reference/clibrary/cstdio/fread/ has an example with reading from a file. It is a c++ page but should work for c


Keep in mind when using fread and fwrite that strange errors can occur in some cases when the file is opened for normal text writing. Opening the file for binary will eliminate this potential problem. It's mainly due to "new lines", which seem for some reason to differ between binary and text file reading and writing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜