C Language
10. File Handling & StreamsAdvanced11 min read

File Handling in C: Reading, Writing & Binary I/O

Persist data to disk using fopen, fclose, fprintf, fscanf, fgets, fputs, binary fread/fwrite, and seek positions with fseek.

Key Takeaways & Core Concepts
  • Files are managed via the FILE* stream pointer defined in <stdio.h>.
  • fopen(path, mode) opens a file stream in modes like "r", "w", "a", "rb", or "wb".
  • Always check if fp == NULL to confirm whether the file opened successfully.
  • Always call fclose(fp) to flush internal buffers and release file descriptors.
  • fseek(), ftell(), and rewind() provide random access navigation within files.

Standard File Access Modes

Common modes used with fopen():

  • "r": Read-only. Fails if the file does not exist.
  • "w": Write-only. Creates file or truncates existing file to 0 length.
  • "a": Append. Writes new data at the end of the file.
  • "r+": Read and write. File must exist.
  • "w+": Read and write. Overwrites existing file.
  • "rb" / "wb": Binary read/write modes (preserves exact byte streams).

Writing and Reading Files in C

Standard file read/write pipeline:

Writing and Reading a Text File Safely
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void) {
5 const char *filename = "codezov_demo.txt";
6
7 // 1. Open file for writing
8 FILE *fp = fopen(filename, "w");
9 if (fp == NULL) {
10 perror("Error opening file for write");
11 return 1;
12 }
13
14 fprintf(fp, "CodeZov C Tutorial\n");
15 fprintf(fp, "Topic: File Handling\n");
16 fprintf(fp, "Score: %d\n", 100);
17 fclose(fp); // Flush and close
18
19 // 2. Open file for reading
20 fp = fopen(filename, "r");
21 if (fp == NULL) {
22 perror("Error opening file for read");
23 return 1;
24 }
25
26 char line[128];
27 printf("Reading contents from %s:\n", filename);
28 while (fgets(line, sizeof(line), fp) != NULL) {
29 printf(">> %s", line);
30 }
31
32 fclose(fp);
33 return 0;
34}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
34 lines
Note: fgets reads one line at a time until reaching EOF, ensuring buffer bounds are never exceeded.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

What value does fopen() return if the target file cannot be opened or does not exist in 'r' mode?

Intermediate