Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

File I/O (`stdio.h`) | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 25 of 50

·c

File I/O (`stdio.h`)

10 mins

Course progress50%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `fopen` returns `NULL` on failure – always test the pointer.
  • `feof(fp)` tells you when end‑of‑file is reached after a failed read.
  • `fread`/`fwrite` are binary‑safe; `fgets`/`fprintf` are text‑oriented.
  • `fflush(fp)` forces buffered data to be written to the file.

Files are accessed through FILE* streams.

FILE *fp = fopen("data.txt", "r");
if (!fp) { perror("open"); exit(EXIT_FAILURE); }

char line[128];
while (fgets(line, sizeof line, fp)) {
    // process line
}

fclose(fp);

Modes:

  • r – read (file must exist).
  • w – write (creates/overwrites).
  • a – append.
  • r+, w+, a+ – read/write variants.

Always check the return of fread, fwrite, fprintf, and close the file with fclose.

Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonStandard Input / Output (`stdio.h`)Continue to lesson 26Preprocessor DirectivesBack to C Programming Fundamentals curriculum