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().

Categorystdio.h I/O
KindLibrary function
Header<stdio.h>
C standardC89 / C90

📝 Syntax

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

⚙️ Parameters

ptr RequiredA pointer to a buffer with room for at least size times nmemb bytes.
size RequiredThe size of each element in bytes.
nmemb RequiredThe maximum number of elements to read.
stream RequiredAn 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏