2

The manual wasn't clear on the subject.

if I tell fread() to read from file 1 item of 1024 bytes each time (in a loop) and the last block is of size < 1024, I know that fread() will return 0.

But, is the buffer going to contain the remainder?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
susdu
  • 852
  • 9
  • 22
  • Reading one item of `1024B` means that if there are less than `1024B` the item is incomplete. – Iharob Al Asimi Jan 08 '16 at 14:41
  • the c spec says nothing about it so it will depend on your c library – Kai Iskratsch Jan 08 '16 at 14:46
  • 1
    I understand this doesn't answer your question, but one solution may be to compute the size of the file initially if unknown and keep track of how many bytes you've read. Once you meet the condition of a remainder being < `1024B` handle this appropriately. – Talaria Jan 08 '16 at 14:49
  • 2
    see also http://stackoverflow.com/questions/8589425/how-does-fread-really-work – terence hill Jan 08 '16 at 14:50
  • One could be inclined to let fread read 1024 objects of size 1. In that case the result is, I think defined. The [open group's man page](http://pubs.opengroup.org/onlinepubs/009695399/functions/fread.html) says "For each object, size calls shall be made to the fgetc() function" -- that should be the same for n objects of size 1. (Oh, I see that @Terence pointed to an answer suggesting just that.) – Peter - Reinstate Monica Jan 08 '16 at 14:59
  • What I understand from @terencehill link is there is basically no difference between the performance of the two cases, since POSIX requires that fread will call fgetc() for each byte read. Is this correct? – susdu Jan 09 '16 at 10:30
  • As far as I understand it, yes.@PeterA.Schneider We can also conclude that any time you need to have the buffer defined it's better to use size 1. Anyway, for critical operations I would test it explicitly, just to be sure ;) – terence hill Jan 09 '16 at 15:32

1 Answers1

3

The Standards says:

7.21.8.1 The fread function

If a partial element is read, its value is indeterminate.

The element in this case is of size 1024 bytes and you read one element. The element, entire block of 1024 bytes, will have an indeterminate value. Reading that value could cause undefined behavior.

And:

The fread function returns the number of elements successfully read, which may be less than nmemb if a read error or end-of-file is encountered.

If you get a return value of 0, then zero elements were successfully read, another indicator that the element wasn't read correctly, and should not be used, as mentioned before.

Community
  • 1
  • 1
2501
  • 25,460
  • 4
  • 47
  • 87