fread() Read a block of data from a stream
fread() Read a block of data from a stream
fread() counts complete fixed-size elements read, not bytes. Short counts can mean EOF or error and omit partial elements; use feof() and ferror().
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
⚙️ Parameters
| ptr Required | A pointer to a buffer with room for at least size times nmemb bytes. |
|---|---|
| size Required | The size of each element in bytes. |
| nmemb Required | The maximum number of elements to read. |
| stream Required | An open stream available for input. |
Returns: Returns the number of complete elements read, not the number of bytes. A short count can indicate end-of-file or an error.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Read 4 items
ABCD
⚠️ Warning The buffer must hold size times nmemb bytes. Check the return value, and do not treat the unread portion as valid data after a short read.
💡 Tip The example writes and then reads an automatically removed temporary file. The cast with %lu prints size_t using C89 facilities.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QDoes fread return a byte count or an element count?
AIt returns the number of complete elements read. Multiply that count by size to obtain the corresponding byte count. A partial final element is not counted; use feof() and ferror() to distinguish EOF from error.
QDoes a short fread count always mean an error?
ANot necessarily; it can also mean normal end-of-file. Use feof() and ferror() to determine the cause.
QHow should I set the size and nmemb arguments for fread?
AFor an array of T, normally use sizeof(T) for size and the desired element count for nmemb, ensuring the destination holds their product. The return value can then be compared directly with the element count. Swapping the arguments may preserve the total bytes requested, but it changes the complete-element granularity and the meaning of a short read, so do not interchange them casually.