How to Use fwrite in C: Syntax, Example, and Tips
In C,
fwrite writes data from memory to a file stream. You provide a pointer to the data, the size of each element, the number of elements, and the file pointer. It returns the number of elements successfully written.Syntax
The fwrite function has this syntax:
ptr: Pointer to the data to write.size: Size in bytes of each element.count: Number of elements to write.stream: File pointer to the open file.
It returns the number of elements actually written, which should match count if successful.
c
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
Example
This example writes an array of integers to a binary file named data.bin using fwrite. It then closes the file.
c
#include <stdio.h> int main() { FILE *file = fopen("data.bin", "wb"); if (file == NULL) { perror("Failed to open file"); return 1; } int numbers[] = {10, 20, 30, 40, 50}; size_t elements_written = fwrite(numbers, sizeof(int), 5, file); if (elements_written != 5) { perror("Failed to write all elements"); fclose(file); return 1; } fclose(file); printf("Successfully wrote %zu integers to data.bin\n", elements_written); return 0; }
Output
Successfully wrote 5 integers to data.bin
Common Pitfalls
- Not opening the file in binary mode (
"wb") when writing binary data can cause data corruption on some systems. - Ignoring the return value of
fwritecan hide write errors. - Passing incorrect sizes or counts can lead to partial writes or memory errors.
- Not checking if the file pointer is
NULLbefore writing causes crashes.
c
#include <stdio.h> int main() { FILE *file = fopen("data.bin", "w"); // Wrong mode for binary data if (file == NULL) { perror("Failed to open file"); return 1; } int numbers[] = {1, 2, 3}; size_t written = fwrite(numbers, sizeof(int), 3, file); if (written != 3) { perror("Write error"); } fclose(file); return 0; } // Correct way: // Use "wb" mode to open file for binary writing. // Always check fwrite return value. // Check file pointer before writing.
Quick Reference
Remember these tips when using fwrite:
- Open files with
"wb"mode for binary writing. - Pass the correct size and count matching your data.
- Check the return value to confirm all data was written.
- Close the file with
fcloseafter writing.
Key Takeaways
Use fwrite to write binary data by specifying pointer, element size, count, and file pointer.
Always open files in binary mode ("wb") when writing binary data to avoid corruption.
Check fwrite's return value to ensure all elements were written successfully.
Verify the file pointer is not NULL before calling fwrite to prevent crashes.
Close files with fclose to flush buffers and release resources.