Example 1 — Write four integers and read them back
Check that fread returns the full count.
#include <stdio.h>
int main(void) {
int out[] = {10, 20, 30, 40};
FILE *fp = fopen("nums.bin", "wb");
if (!fp) return 1;
fwrite(out, sizeof out[0], 4, fp);
fclose(fp);
int in[4];
fp = fopen("nums.bin", "rb");
if (!fp) return 1;
size_t got = fread(in, sizeof in[0], 4, fp);
fclose(fp);
printf("read %zu ints:", got);
for (size_t i = 0; i < got; i++) printf(" %d", in[i]);
printf("\n");
return 0;
} How It Works
fwritecopies 16 bytes (4 ints) to the file.freadreturns how many whole items it read.- Reading with the same type and platform restores the values exactly.
