Chapter 14: File Handling

This is one of the most important and practical topics in C programming. Until now, all our data was lost when the program ended. With file handling, we can save data permanently on the hard disk and read it back anytime – even after closing the program.

C provides powerful functions to work with files:

  • Open a file
  • Read from it
  • Write to it
  • Close it
  • Move around inside it (random access)

All file handling functions are declared in <stdio.h> header.

1. Opening and Closing Files

Opening a file:

C
  • FILE * is a special pointer type for files
  • fopen() returns NULL if file cannot be opened

Common Modes:

Mode Meaning Creates file if not exist? Starts from
“r” Read only No Beginning
“w” Write only (overwrites if exists) Yes Beginning
“a” Append (add at end) Yes End
“r+” Read + Write No Beginning
“w+” Read + Write (overwrites) Yes Beginning
“a+” Read + Append Yes End

Closing a file:

C

Always close files when you’re done – otherwise data may be lost or file may get corrupted.

Example – Open and Close a File

C

2. Writing to Files

fprintf() – Like printf(), but writes to file

fputs() – Writes a string to file

Example – Write some data to file

C

Output on screen:

text

Inside student.txt file:

text

3. Reading from Files

fscanf() – Like scanf(), but reads from file fgets() – Reads a whole line (including spaces)

Example – Read data from file

C

Output:

text

4. Random Access Files (fseek, ftell)

ftell() – Returns current position in file (in bytes) fseek() – Moves file pointer to any position

Syntax of fseek():

C
  • whence:
    • SEEK_SET → from beginning
    • SEEK_CUR → from current position
    • SEEK_END → from end

Example – Read specific line or move around

C

5. Best Practices & Important Tips

  • Always check if fopen() returned NULL
  • Always fclose() when done
  • Use “rb” / “wb” for binary files (images, executables)
  • Don’t forget to include <stdio.h>
  • Use fgets() instead of gets() – safer (no buffer overflow)
  • For large files, use buffering or read in chunks

Today’s Homework

  1. Write a program that takes student details (name, roll, marks) from user and writes them to a file.
  2. Write a program that reads the file created above and prints the student details in a nice format.
  3. Create a program that appends new student data to the existing file (use mode “a”).
  4. Write a program that counts how many lines are there in a text file (use fgets() in a loop).
  5. Create a program that copies content from one file to another (character by character or line by line).

You may also like...