Binary reads and writes in C
fread and fwrite move records, and both return how many they handled.
#include <stdio.h>
typedef struct {
int id;
double score;
} Record;
size_t save_records(const char *path, const Record *rows, size_t n) {
FILE *f = fopen(path, "wb");
if (f == NULL) {
return 0;
}
size_t written = fwrite(rows, sizeof(Record), n, f);
fclose(f);
return written;
}
size_t load_records(const char *path, Record *rows, size_t max) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return 0;
}
size_t read = fread(rows, sizeof(Record), max, f);
fclose(f);
return read;
}
How it works
- The element size and count are separate arguments.
- A short return value means end of file or an error.
- Struct layout differs between machines, so this is not a portable format.
Keywords and builtins used here
FILENULLcharconstdoubleifintload_recordsreturnsave_recordssize_tsizeofstructtypedef
The run, in numbers
- Lines
- 26
- Characters to type
- 481
- Tokens
- 150
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 90 seconds.
Step 2 of 4 in Writing & binary, step 6 of 12 in Files & I/O.