File Handling in C
# CHAPTER 17
File Handling in C
1. Introduction
Until now, all data in our programs was stored in RAM. When the program exited, the data was lost forever (Volatile Memory). To make data permanent (Persistent Memory), we must save it to a file on the hard drive. C provides powerful built-in functions in<stdio.h> for File Handling.
2. Learning Objectives
By the end of this chapter, you will be able to:- Open files in different modes (read, write, append).
-
Use a
FILEpointer.
-
Write text to files using
fprintf()andfputs().
-
Read text from files using
fscanf()andfgets().
- Close files properly to prevent data corruption.
3. The FILE Pointer and fopen()
To interact with a file, you need a pointer of type FILE. You open a file using the fopen() function, which requires the file name and the "mode".
Common Modes:
-
"r": Read mode. (Returns NULL if file doesn't exist).
-
"w": Write mode. (Creates a new file. If the file exists, it erases all contents!).
-
"a": Append mode. (Creates a new file or adds data to the end of an existing file).
4. Writing to a File
To write formatted text to a file, usefprintf(). It works exactly like printf(), but takes the file pointer as its first argument.
5. Reading from a File
To read formatted text, usefscanf(). To read a full line (including spaces), use fgets().
Reading a full line using fgets():
6. Mini Project: Notes Storage System
Let's build a program that asks the user for a note and saves it permanently to a text file.7. Memory-Level Explanation
When you callfopen(), the Operating System steps in. It locates the file on the hard drive (HDD/SSD) and loads a chunk of it into a temporary buffer in RAM. The FILE * pointer points to this buffer structure.
When you write using fprintf(), you are actually writing to the RAM buffer. It is only when you call fclose() (or the buffer fills up) that the OS "flushes" the buffer and physically writes the data to the hard drive. If you forget to call fclose() and the program crashes, your data may be lost!
8. Common Mistakes
-
Forgetting
fclose(): Results in memory leaks and missing data in the file.
-
Using
"w"instead of"a": You wanted to add a line, but"w"wiped the whole 10,000-line database!
-
Not checking for NULL: If you try to read a file that doesn't exist,
fopenreturnsNULL. If you passNULLtofgets, the program will crash (Segmentation Fault).
9. Exercises
-
1.
Write a program that asks for the user's name and age, and writes it to
users.txt.
-
2.
Write a second program that opens
users.txtin"r"mode and prints its contents to the screen.
10. MCQ Quiz with Answers
What data type is required to manage a file in C?
Which mode is used to add data to the end of an existing file?
What does fopen("data.txt", "w") do if the file already exists?
What does fopen() return if the file cannot be opened?
Which function writes formatted data to a file?
Which function is used to read a full line containing spaces from a file?
Why is fclose() essential?
Which mode opens a file for reading?
If a file is opened in "r" mode, and it does not exist, what happens?
fprintf() to print to the screen?
a) Yes, by passing stdout as the file pointer b) No, only to files
Answer: a) Yes, by passing stdout as the file pointer
11. Interview Questions
-
Q: Explain the difference between text mode (
"w") and binary mode ("wb") in C file handling.
-
Q: Why is it dangerous to ignore the return value of
fopen()?
-
Q: Explain the concept of the file buffer and why
fflush()orfclose()is necessary.
12. Summary
File handling allows data to persist after the program exits. We use aFILE * pointer and fopen() to access files in read ("r"), write ("w"), or append ("a") modes. fprintf and fgets handle writing and reading. Always remember to fclose() the file when finished!