1

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

2
  • I would suggest you to use a buffer of 2 bytes and then try reading the one byte from the file. Commented Jan 28, 2011 at 16:40
  • @Ashwini, care to explain why? Commented Jan 28, 2011 at 16:43

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

+1, but you should prefer fgetc to getc, since the latter could be implemented as a macro that evaluates its FILE* parameter more than once.
@Adam: As such, getc could be noticably faster. The only argument is of type FILE *, so unless you're passing the return value of a function that returns a FILE * or something like files[i++], the number of times the argument is evaluated is probably irrelevant. Such usage seems pretty rare and pathological to me.
0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.