C - File Input Output

Overview

File I/O in C uses the stdio library to read from and write to files via FILE pointers. Common operations include opening a file, reading/writing data, and closing the file.

Learning Objectives

  • Open files using fopen and close them with fclose.
  • Read and write text data with fprintf, fscanf, fgets, and fputs.
  • Handle errors and check return values safely.

Prerequisites

Basic Example: Write then Read

#include <stdio.h>

int main(void) {
  FILE *fp = fopen("data.txt", "w");
  if (!fp) { perror("fopen write"); return 1; }
  fprintf(fp, "Hello %d\n", 42);
  fclose(fp);

  fp = fopen("data.txt", "r");
  if (!fp) { perror("fopen read"); return 1; }
  char buf[64];
  if (fgets(buf, sizeof buf, fp)) {
    printf("Read: %s", buf);
  }
  fclose(fp);
}

Expected Output

Read: Hello 42

Reading structured data

#include <stdio.h>

typedef struct { char name[32]; int age; } Person;

int main(void) {
  FILE *fp = fopen("people.txt", "w");
  if (!fp) return 1;
  fprintf(fp, "Ann 30\nBen 25\n");
  fclose(fp);

  fp = fopen("people.txt", "r");
  if (!fp) return 1;
  Person p;
  while (fscanf(fp, "%31s %d", p.name, &p.age) == 2) {
    printf("%s (%d)\n", p.name, p.age);
  }
  fclose(fp);
}

Expected Output

Ann (30)
Ben (25)

Common Pitfalls

  • Forgetting to close files (fclose), leading to resource leaks.
  • Not checking return values from fopen, fgets, or fscanf.
  • Using fscanf without width limits can overflow buffers; use field widths (e.g., %31s).

Exercises

  1. Write a program that appends a new line to a log file with a timestamp-like integer.
  2. Read a file line by line and count the number of lines that contain a given word.