CodeBlanks Logo Icon CodeBlanks

Summary - File I/O

  • C course
  • Intermediate
  • Lesson 52/116
  • 5 min

Combine fopen, fprintf and fgets to write a notes app.

Summary - File I/O

In this summary you'll combine file I/O concepts to write a notes app. Throughout the group you learned fopen, fprintf, fscanf, fgets, fputs, fclose, fread and fwrite.

The notes app uses these parts: opening a file with fopen, writing a note with fprintf, closing with fclose, reopening with fopen, reading with fgets and printing to screen with printf. These parts form the foundation for real-world journals, configuration files and text editors. File I/O is how C makes data persistent.

Practice Write a notes app

Open with FILE *f = fopen("not.txt", "w"); (check NULL). Write a note with fprintf(f, "Bugün ders var\n");, fclose(f);. Reopen with f = fopen("not.txt", "r"); (check NULL). Declare char note[128];; read with fgets(note, sizeof(note), f);. fclose(f);. Print with printf("Not: %s", note);.

Starter code

main.c
#include <stdio.h>

// Open not.txt with fopen (write mode)
// Write a note with fprintf, close with fclose
// Reopen in read mode, read with fgets, close
// Print the note with printf

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    FILE *f = fopen("not.txt", "w");
    if (f == NULL) return 1;
    fprintf(f, "Bugün ders var\n");
    fclose(f);

    f = fopen("not.txt", "r");
    if (f == NULL) return 1;
    char note[128];
    fgets(note, sizeof(note), f);
    fclose(f);

    printf("Not: %s", note);
    return 0;
}

Expected output

Not: Bugün ders var

Summary

In this group you learned file I/O concepts: fopen, fprintf, fscanf, fgets, fputs, fclose, fread and fwrite.

You combined them to write a notes app. These functions are the foundation of making data persistent in C: configuration files, logs, reports and binary data files are written with them. In the next groups you'll make these operations more robust with error handling; errno, perror and assert will let you handle unexpected situations safely. Robust file I/O is the backbone of real-world C projects.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which function opens a file for reading?

  • fread
  • fopen("dosya", "r") Correct answer
  • fgets
  • fclose

Explanation: fopen with "r" mode opens a file for reading.

2 Match functions to purpose

Term Meaning
fopen Open file
fprintf Formatted write
fgets Line read
fclose Close file

All lessons in Intermediate