Skip to content
Guest
Learn C · Course Syllabus Show lessons
Systems Programming · 8 min read · Intermediate

File I/O & Safe Error Handling

Open, write, read, and close files with fopen/fprintf/fgets/fclose, and handle errors cleanly with errno and return codes.

What you'll learn

  • Check FILE * pointers for NULL immediately after fopen()
  • Read lines safely using bounded fgets() instead of unsafe gets()
  • Report errors cleanly to stderr and return non-zero exit codes

C does not have exceptions (try/catch). Instead, standard library functions signal failure via return values (NULL, -1, or non-zero error codes) and set errno. Always check FILE *f = fopen(...) before reading or writing, and always call fclose(f).

Fill-in-the-Blank Exercise

Safe File Open & Close

Open a file for writing, check for NULL, and close it cleanly.

FILE *fp = ("notes.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "Saved!\n");
(fp);

Live Code Lab

Cfile_io.c
Expected OutputClick “Run Live” to compile with GCC 13 (C11)
Read: DevPath C11 File I/O

Check Your Understanding

Score: 0 / 1

1. Why should C programs use fgets(buf, sizeof(buf), fp) instead of gets(buf)?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind