fread() / fwrite()
Functions for reading and writing binary data directly to and from a file. Unlike text mode, no newline conversion is performed, so you can accurately handle binary files such as images, audio, and struct data.
Syntax
// Reads binary data from a file. // Return value: the number of blocks read (check with feof() or ferror()). size_t fread(void *ptr, size_t size, size_t count, FILE *stream); // Writes binary data to a file. // Return value: the number of blocks written (if different from count, an error occurred). size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
Parameters
| Parameter | Description |
|---|---|
| ptr | The buffer to store data into (for reading), or the starting address of the data to write (for writing). |
| size | The size of one block in bytes. For a struct, pass sizeof(struct X). |
| count | The number of blocks to read or write. |
| stream | A FILE pointer opened with "rb" or "wb". |
Sample Code
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
double score;
} Record;
int main(void) {
// Writes struct data to a binary file.
Record rec = {42, 98.5};
FILE *fp = fopen("data.bin", "wb"); // Opens the file in binary write mode.
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
size_t written = fwrite(&rec, sizeof(Record), 1, fp);
if (written != 1) {
fprintf(stderr, "Write failed.\n");
}
fclose(fp);
// Reads struct data from the binary file.
Record rec2 = {0};
fp = fopen("data.bin", "rb"); // Opens the file in binary read mode.
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
size_t read_count = fread(&rec2, sizeof(Record), 1, fp);
fclose(fp);
if (read_count == 1) {
printf("id = %d\n", rec2.id); // Outputs: id = 42
printf("score = %.1f\n", rec2.score); // Outputs: score = 98.5
}
return 0;
}
Notes
Always specify binary mode ("rb", "wb", "ab") when opening a file. Opening in text mode causes automatic newline conversion ('\n' ↔ "\r\n") on Windows, which will corrupt binary data.
If the return value of fread() is less than the requested count, it means either the end of file (EOF) was reached or an error occurred. Use feof() / ferror() to determine the cause.
Reading or writing multiple blocks at once reduces the number of system calls and improves performance. You can control the file position with fseek().
If you find any errors or copyright issues, please contact us.