C ยท Chapter 35 of 45

C File Handling

C programs can read from and write to files using the <stdio.h> file functions, centered around the FILE pointer type. fopen() opens a file, and fclose() closes it when finished.

Common operations include fprintf()/fscanf() for formatted text, and fgets()/fputs() for reading and writing lines of text.

Syntax
FILE *f = fopen("file.txt", "w");
fclose(f);

Opening and closing files

fopen("name", "mode") opens a file in a mode like "r" (read), "w" (write, overwrites), or "a" (append), and returns a FILE* (or NULL on failure). Always call fclose() when done.

Reading and writing

fprintf(file, ...) writes formatted text to a file just like printf does to the screen. fgets(buffer, size, file) reads a line of text into a buffer safely.

Example 1 (c)
#include <stdio.h>

int main() {
  FILE *f = fopen("out.txt", "w");
  if (f != NULL) {
    fprintf(f, "Hello, file!\n");
    fclose(f);
  }
  return 0;
}
Output
(creates out.txt containing: Hello, file!)

The file is opened for writing, written to, then closed.

Example 2 (c)
#include <stdio.h>

int main() {
  FILE *f = fopen("out.txt", "r");
  char line[100];
  if (f != NULL) {
    fgets(line, 100, f);
    printf("%s", line);
    fclose(f);
  }
  return 0;
}
Output
Hello, file!

fgets reads a line from the opened file into the buffer, which is then printed.

Key points

  • fopen() opens a file and returns a FILE pointer (or NULL on failure).
  • Common modes are "r" (read), "w" (write/overwrite), and "a" (append).
  • Always check for NULL and call fclose() when finished with a file.
  • fprintf/fscanf and fgets/fputs handle formatted and line-based I/O.
๐Ÿ’ก Note: Forgetting to close a file can leave data unwritten to disk or exhaust available file handles.

๐Ÿ“ Quick Quiz

1. What does fopen() return if it fails to open a file?

2. Which mode opens a file for appending without erasing its content?

3. What function should you call when finished with a file?