🎓 Unit 9: File Handling in C++
What is File Handling?
- File handling is the process of reading and writing data to files.
- It allows you to store the output of a program in a file and also read file data onto the console.
- The primary purpose is to permanently save data that would otherwise be lost when a program finishes execution (data stored in RAM is temporary).
How Normal Programs Differ from File Handling:
- Normally, when you create a program, input is given from the keyboard, processed by the program, and output is printed on the console. This data is typically stored in RAM (Random Access Memory) and is lost once the program terminates or the terminal is closed.
- With file handling, instead of data being stored temporarily in RAM, you can instruct your program to create a file and write the input/output to that file, which then gets permanently saved on secondary storage (e.g., hard disk). You can then read this data back to the console whenever needed.
C++ uses streams to perform I/O. A stream is a sequence of bytes.
✍️ 1. Stream-Based Input/Output
C++ uses streams to perform I/O operations:
- Input stream: Reads data (e.g.,
cin, ifstream)
- Output stream: Writes data (e.g.,
cout, ofstream)
Main file stream classes from <fstream>:
ifstream: Input file stream (read from files)
ofstream: Output file stream (write to files)
fstream: Combined input and output stream
Syntax: