4 ms·
Shouldn't you be using cppreference.com instead of cplusplus.com? Because the former [0] actually has this language: Reads up to "count" objects into the a
by Joker_vD 4mo ago
Shouldn't you be using cppreference.com instead of cplusplus.com? Because the former [0] actually has this language:
Reads up to "count" objects into the array "buffer" from the given input stream "stream"
as if by calling fgetc "size" times for each object, and storing the results, in the order
obtained, into the successive positions of buffer, which is reinterpreted as an array of
"unsigned char".
This whole fread/fwrite's interface is hailing from the time where some OSes used record-based filesystems and were literally unable to read/write less than a record at a time.
[0] https://en.cppreference.com/c/io/fread https://en.cppreference.com/c/io/fread
- Someone 4mo agoMaybe, but that text says “as if” and even “If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.” so it doesn’t in any way require implementations to implement it by actually reading one byte at a time. That description also fits what I saw in the implementations I inspected, both of which simply try to read size × count bytes.
- Joker_vD 4mo agoBy the way, behold the original (from UNIX Version 7) stdio package [0]: fread(ptr, size, count, iop) unsigned size, count; register char *ptr; register FILE *iop; { register c; unsigned ndone, s; ndone = 0; if (size) for (; ndone<count; ndone++) { s = size; do { if ((c = getc(iop)) >= 0) *ptr++ = c; else return(ndone); } while (--s); } return(ndone); } Thankfully, the definition of getc() [1] is indeed #define getc(p) (--(p)->_cnt>=0? *(p)->_ptr++&0377:_filbuf(p)) Interestingly enough, because there is no explicit multiplication, this loop properly works on systems with e.g. 16-bit unsigned int but 32-bit pointers (and overflows just the same on systems where ints and pointers are the same size). [0] https://github.com/v7unix/v7unix/blob/master/v7/usr/src/libc/stdio/rdwr.c https://github.com/v7unix/v7unix/blob/master/v7/usr/src/libc... [1] https://github.com/v7unix/v7unix/blob/master/v7/usr/include/stdio.h#L29 https://github.com/v7unix/v7unix/blob/master/v7/usr/include/...