fwrite() Write a block of data to a stream

fwrite() Write a block of data to a stream

fwrite() writes fixed-size elements and returns the complete-element count; short counts indicate error. Structure dumps vary in byte order and padding.

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

📝 Syntax

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

⚙️ Parameters

ptr RequiredA pointer to a buffer containing at least size times nmemb bytes of valid data.
size RequiredThe size of each element in bytes.
nmemb RequiredThe number of elements to write.
stream RequiredAn open stream available for output.

Returns: Returns the number of complete elements written. A value smaller than nmemb indicates a write error.

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

10 20 30
⚠️ Warning size and nmemb must describe the actual elements; an undersized buffer would make fwrite read beyond its valid storage.
💡 Tip The example verifies the data with an update-capable temporary file, which is removed automatically when closed.

📚 Related Tutorials

❓ FAQ

QDoes fwrite return the number of bytes written?
ANo. It returns the number of complete elements written, so compare it directly with nmemb to check for completion.
QCan a structure written with fwrite be read directly on another platform?
ANot necessarily. Byte order, padding, and type sizes can differ. A portable file format should define an explicit field encoding rather than dump structure memory.
QHow should I set element size and count when writing a string with fwrite?
ATo write string contents without the terminator, commonly use fwrite(s, 1, strlen(s), stream). Each element is one byte, so the return value can be compared with strlen(s). If the file format requires the terminating null character, use the length plus one as the element count; do not accidentally write a null character into plain text.
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%

🙏 帮我们做得更好

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

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