user000
user000

Reputation: 63

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 error. any idea what can be wrong. im sure pFile is fine.

thanks

Upvotes: 1

Views: 2768

Answers (4)

Codesmith
Codesmith

Reputation: 6792

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.

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215557

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.

Upvotes: 1

Mike
Mike

Reputation: 8555

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

Upvotes: 0

user405725
user405725

Reputation:

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.

Upvotes: 2

Related Questions