Fread number of bytes limit

2019-07-18 17:44发布

问题:

Does fread have a limit for the number of bytes it can read at once? Or I can read any size I would like to charge in to my pointer? For example, Can I read file of 50MB once using fread to charge it into char pointer?

回答1:

Theoretically, yes, it can read any number of bytes up to the maximum of size_t (which is an unsigned int (roughly 4GB on a 32-bit system). However, since your buffer will have to be allocated in a contiguous block, it is not likely to be feasible, nor advisable, to read in a large file at once (and for substantially large files, you will probably fail to create a memory buffer large enough to hold the file). Typically, you will have a smaller buffer and loop over the file loading it into memory in chunks.



回答2:

In practice, fread() will have no problem slurping in a 50MB file. That's not really a “large file” by modern standards. fread() returns the number of items read, and is guaranteed to return a short item count only on end-of-file (if you asked for more items than are in the file) or error. You must check that the returned item count is what you expect and, if it is short, use feof() and ferror() to distinguish between EOF and error.