█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Programming Languages/C/File I/O
40 minIntermediate

File I/O

After this lesson, you will be able to: Use fopen, fread, fwrite, fclose, fprintf, fscanf for text + binary file I/O.

File I/O is identical across Unix + Windows in standard C.

Prerequisites:Structs

Text file reading + writing

Open → read/write → close.

tsx
#include <stdio.h>
int main(void) {
// Write
FILE *f = fopen("out.txt", "w");
if (f == NULL) { perror("fopen"); return 1; }
fprintf(f, "Hello, %s\n", "world");
fclose(f);
// Read line by line
f = fopen("out.txt", "r");
if (f == NULL) { perror("fopen"); return 1; }
char buf[256];
while (fgets(buf, sizeof(buf), f) != NULL) {
printf("%s", buf);
}
fclose(f);
return 0;
}

Binary I/O

For structured / non-text data.

tsx
typedef struct { int id; double balance; } Record;
int main(void) {
Record records[] = { {1, 100.0}, {2, 250.5}, {3, 99.99} };
FILE *f = fopen("records.bin", "wb");
fwrite(records, sizeof(Record), 3, f);
fclose(f);
Record loaded[3];
f = fopen("records.bin", "rb");
size_t read = fread(loaded, sizeof(Record), 3, f);
fclose(f);
printf("Read %zu records\n", read);
return 0;
}
// Caveat: binary formats are NOT portable across architectures (endianness, struct padding).
// For cross-platform: use a defined format (JSON, protobuf, flatbuffers) or write byte-by-byte.

Error handling pattern

Always check + close.

tsx
FILE *f = fopen(path, "r");
if (f == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", path, strerror(errno));
return -1;
}
// ... use f ...
if (ferror(f)) {
fprintf(stderr, "Read error\n");
}
if (fclose(f) != 0) {
perror("fclose");
}

Common mistakes only experienced C devs avoid

Forgetting fclose. Leaks file descriptors. Not checking fopen's return value. Crash on next fread. Using fgets without checking the buffer for the newline. May truncate. Binary I/O without thinking about endianness + struct padding. Cross-platform pain.

Quick Check

Why might binary I/O of a struct break when moving the file between machines?

Pick the cleanest answer.

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Structs and Unions
Back to C
The C Standard Library→