C
fread and fwrite
Learn binary read/write with fread and fwrite.
fread and fwrite
fread and fwrite are the basic way to read and write binary data to/from a file. They're used for structured data, not text; for example arrays and structs.
Example: int arr[3] = {1, 2, 3}; fwrite(arr, sizeof(int), 3, f);. This writes 3 integers to the file. fread(arr2, sizeof(int), 3, f); reads them back. Parameters: data pointer, element size, element count, file. Binary modes "wb" and "rb" are used; this matters for cross-platform consistency.
fwrite parameters
fwrite has four parameters: data pointer, element size, element count, and file. This structure lets you write multiple elements efficiently in one call.
Example: int x = 42; fwrite(&x, sizeof(int), 1, f);. Writes a single integer. Or int arr[10]; fwrite(arr, sizeof(int), 10, f); writes ten integers. sizeof(int) is 4 on most platforms; but using sizeof rather than hardcoding preserves portability. fread has the same parameter structure; it returns the number of elements read.
Exercise Write a binary array and read back
Declare int arr[3] = {10, 20, 30};. Open with FILE *f = fopen("nums.bin", "wb"); (check NULL). Write with fwrite(arr, sizeof(int), 3, f);, fclose(f);. Declare int arr2[3];; reopen with f = fopen("nums.bin", "rb"); (check NULL). Read with fread(arr2, sizeof(int), 3, f);, fclose(f);. Print with printf("%d %d %d\n", arr2[0], arr2[1], arr2[2]);.
Show example solution
#include <stdio.h>
int main(void) {
int arr[3] = {10, 20, 30};
FILE *f = fopen("nums.bin", "wb");
if (f == NULL) return 1;
fwrite(arr, sizeof(int), 3, f);
fclose(f);
int arr2[3];
f = fopen("nums.bin", "rb");
if (f == NULL) return 1;
fread(arr2, sizeof(int), 3, f);
fclose(f);
printf("%d %d %d\n", arr2[0], arr2[1], arr2[2]);
return 0;
}
Test yourself
-
Match fread/fwrite concepts
- fwrite
- Binary write
- fread
- Binary read
- sizeof(int)
- Element size
- 3
- Element count
-
Complete the fwrite call
int x = 42;
fwrite(&x, sizeof(int), ____, f);
Show answer
int x = 42;
fwrite(&x, sizeof(int), 1, f);
-
What does fwrite's second parameter specify?
- Size of each element
- Total bytes
- Buffer pointer
- File name
Show answer
Size of each element — The second parameter is the size of each element (like sizeof(int)).
Next lesson: Summary - File I/O