C Language | Advanced Features | Binary Files - fwrite(), fread()

This article explains how to read and write raw binary data with standard C functions.

Raw Data

Text functions such as fprintf() and fscanf() convert values to and from text. Binary files store memory data directly, which is useful for arrays and structures.

Use fwrite() to write binary data.

size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);

buffer points to the data, size is the size of each item, count is the number of items, and stream is the destination. The function returns the number of items written.

Open binary output files with a mode such as "wb".

Code 1

#include <stdio.h>

typedef struct { int left, top, right, bottom; } RECT;

int main() {
 RECT rect = { 10, 20, 30, 40 };
 FILE *file = fopen("rect.dat", "wb");
 if (file == NULL) return 1;
 fwrite(&rect, sizeof(RECT), 1, file);
 fclose(file);
 return 0;
}

Use fread() to read binary data.

size_t fread(void *buffer, size_t size, size_t count, FILE *stream);

Open binary input files with "rb". The destination buffer must have enough memory.

Code 2

#include <stdio.h>

typedef struct { int left, top, right, bottom; } RECT;

int main() {
 RECT rect;
 FILE *file = fopen("rect.dat", "rb");
 if (file == NULL) return 1;
 fread(&rect, sizeof(RECT), 1, file);
 fclose(file);
 printf("%d %d %d %d\n", rect.left, rect.top, rect.right, rect.bottom);
 return 0;
}

Binary files can depend on details such as data sizes and byte order, so use them carefully when exchanging data between systems.