Lesson 43 of 50 · c
File I/O – Binary Files
Duration: 10 mins
Binary files store raw bytes without newline translation.
FILE *fp = fopen("data.bin", "wb");
int vals[5] = {10,20,30,40,50};
fwrite(vals, sizeof vals, 1, fp);
fclose(fp);
Reading:
FILE *fp = fopen("data.bin", "rb");
int vals[5];
fread(vals, sizeof vals, 1, fp);
Always check the return of fwrite/fread for the number of items written/read.
📚 Example: Storing a Struct to Disk
#include <stdio.h>
#include <stdint.h>
struct Record {
uint32_t id;
double value;
char name[16];
};
int main(void) {
struct Record r = { 42, 3.1415, "sample" };
FILE *f = fopen("record.bin", "wb");
if (!f) return 1;
fwrite(&r, sizeof r, 1, f);
fclose(f);
return 0;
}