Lesson 43 of 50
cFile I/O – Binary Files
10 mins
Course progress86%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 43 of 50
c10 mins
Keep these ideas in mind as you work through the lesson.
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.
#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;
}