The size and count parameters
What you'll learn: How to use the two numerical arguments in fread and fwrite to precisely control how much data moves between your memory and a binary file.
When you work with text files, you often think in lines or characters. But in binary mode, the computer sees everything as raw bytes. To make sense of this, the functions fread() and fwrite() ask you for two specific numbers: size and count.
Thinking in Egg Cartons
Imagine you are moving eggs from a large crate into refrigerators. To do this efficiently, you use egg cartons.
- Size is the capacity of one carton (e.g., 12 eggs).
- Count is how many cartons you want to move in one go.
If you move 3 cartons (count) that each hold 12 eggs (size), you’ve moved 36 eggs total. In C, if you want to save an array of 5 integers to a file, the "size" is the size of one integer (sizeof(int)), and the "count" is 5.
Why two numbers instead of one?
You might wonder: "Why not just provide one number for the total bytes?" While you could technically set size to 1 and count to the total bytes, splitting them provides a major advantage: Return values.
These functions return the number of full items successfully processed, not the number of bytes. If you try to read 10 integers but the file ends after 8 and a half, the function returns 8. This makes it much easier to detect if a record was cut off or if you've reached the end of a clean list of data structures.
Putting it into code
Here is how you typically see these parameters used when saving a custom structure:
#include <stdio.h>
struct Player {
int id;
int score;
};
int main() {
struct Player team[3] = {{1, 500}, {2, 750}, {3, 900}};
FILE *file = fopen("team.dat", "wb");
if (file != NULL) {
// Size: sizeof(struct Player) - the size of one "carton"
// Count: 3 - how many "cartons" we are moving
size_t items_written = fwrite(team, sizeof(struct Player), 3, file);
printf("Successfully wrote %zu players to the file.", items_written);
fclose(file);
}
return 0;
}
By passing sizeof(struct Player) as the size, you tell C exactly how big one "unit" of data is. The count then tells C how many of those units to grab from your array.
Key takeaway
The size parameter defines the byte size of a single data unit, while count defines how many of those units to process.