Binary files and fixed-size records
Use fread and fwrite for byte-oriented records while understanding portability and validation limits.
After this lesson
You should be able to
- Read and write a known number of binary records.
- Explain why raw structure bytes are not a universal interchange format.
Count objects, then verify the count
Open binary streams with modes such as "rb", "wb", or "ab". fwrite writes a number of objects of a given size and returns how many objects succeeded. fread follows the same object-count model.
A short count may indicate an error or end-of-file, depending on the operation. Never assume the whole record was transferred merely because the function was called.
struct Student student = {23, "Anu", 87.5};
if (fwrite(&student, sizeof student, 1, file) != 1) {
fprintf(stderr, "Write failed\n");
}
struct Student loaded;
if (fread(&loaded, sizeof loaded, 1, file) == 1) {
printf("%s\n", loaded.name);
}Fast locally is not portable forever
A structure may contain padding, and integer or floating representations can vary across platforms or compiler settings. Writing raw structure bytes is suitable only when the reader uses the compatible representation and the file is treated as implementation-specific.
For durable exchange, define a format with explicit field sizes, byte order, version, and validation. Pointers must never be persisted as meaningful links because their addresses are valid only in one running process.
Try it yourself
Write an array of count Student records and detect a short write.
Need a hint?
Compare fwrite's return value with count.
Check the worked solution
Pass sizeof students[0] as the object size and count as the object count.
size_t written = fwrite(students, sizeof students[0], count, file);
if (written != count) {
fprintf(stderr, "Only %zu of %zu records written\n", written, count);
}Quick check
Why should a pointer field not be restored from raw file bytes?
Why this lesson exists
Syllabus mapping
Binary files · Reading and writing structures in binary files
Maps to course outcomes CO3, CO4, CO5.