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.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
⚙️ Parameters
| ptr Required | A pointer to a buffer containing at least size times nmemb bytes of valid data. |
|---|---|
| size Required | The size of each element in bytes. |
| nmemb Required | The number of elements to write. |
| stream Required | An 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 stdio.h functions
📚 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.