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.
Open → read/write → close.
#include <stdio.h>int main(void) {// WriteFILE *f = fopen("out.txt", "w");if (f == NULL) { perror("fopen"); return 1; }fprintf(f, "Hello, %s\n", "world");fclose(f);// Read line by linef = 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;}
For structured / non-text data.
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.
Always check + close.
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");}
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.
Pick the cleanest answer.
Sign in and purchase access to unlock this lesson.