CodeBlanks Logo Icon CodeBlanks

fread and fwrite

  • C course
  • Intermediate
  • Lesson 51/116
  • 5 min

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.

Practice 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]);.

Starter code

main.c
#include <stdio.h>

// Open nums.bin with fopen (binary write mode)
// Declare int arr[3] = {10, 20, 30}, write with fwrite
// fclose, then reopen in read mode
// Read with fread, print with printf

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

10 20 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match fread/fwrite concepts

Term Meaning
fwrite Binary write
fread Binary read
sizeof(int) Element size
3 Element count

2 Complete the fwrite call

Question
int x = 42;
fwrite(&x, sizeof(int), ____, f);
Answer
int x = 42;
fwrite(&x, sizeof(int), 1, f);

Explanation: Writing one element means count is 1.

3 What does fwrite's second parameter specify?

  • Size of each element Correct answer
  • Total bytes
  • Buffer pointer
  • File name

Explanation: The second parameter is the size of each element (like sizeof(int)).

All lessons in Intermediate