File I/O allows a C++ program to read from and write to files on a disk. This is essential for Data Persistence, allowing information to be saved even after the program is closed or the computer is turned off.
In C++, file handling is performed using the <fstream> library, which provides three main classes:
ofstream: Output File Stream (Used to create/write files).
ifstream: Input File Stream (Used to read files).
fstream: File Stream (Can do both reading and writing).
Theoretically, C++ treats files as Streams. A stream is an abstraction that represents a flow of data between a source and a destination.
Think of a stream as a "conveyor belt" of bytes.
When you write to a file, you are "pushing" data into the stream.
When you read from a file, you are "pulling" data out of the stream.
This is why we use the same operators as cout and cin (<< and >>).
Accessing a physical disk is thousands of times slower than accessing RAM. To solve this, C++ uses a Buffer (a temporary area in RAM).
When you write data, it goes into the buffer first.
Once the buffer is full, or when the file is closed, the data is "flushed" to the disk all at once. This significantly improves performance by reducing the number of times the hardware must be accessed.
When you open a file, you can specify how it should be opened using "ios flags":
| Flag | Meaning |
| ios::out | Open for writing (default for ofstream). |
| ios::in | Open for reading (default for ifstream). |
| ios::app | Append mode. New data is added to the end of the file. |
| ios::trunc | Truncate. If the file exists, its contents are deleted (default for out). |
| ios::ate | At The End. Opens the file and moves the "cursor" to the end. |
| ios::binary | Opens the file in binary mode instead of text mode. |
A safe and robust file operation follows a strict theoretical lifecycle:
Opening: The program requests the Operating System (OS) for a "File Handle." The OS checks if the file exists and if you have permission to access it.
Validation: It is critical to check if the file opened successfully. If the file is missing or read-only, the stream will enter a "fail state."
Positioning (The File Pointer): The OS maintains a "Get Pointer" (for reading) and a "Put Pointer" (for writing). As you read/write, these pointers move forward. You can manually move them using functions like seekg() (seek get) and seekp() (seek put).
Closing: When you close a file, the buffer is flushed, the File Handle is returned to the OS, and memory is freed.
Theoretical Risk: If you don't close a file and the program crashes, the data still in the buffer might be lost forever.
This program demonstrates creating a file, writing to it, and then reading the contents back.
#include <iostream> #include <fstream> // Essential for File I/O #include <string> using namespace std; int main() { string fileName = "example.txt"; // --- WRITING TO A FILE --- ofstream outFile(fileName); // Create and open file if (outFile.is_open()) { outFile << "Line 1: Learning C++ File I/O." << endl; outFile << "Line 2: Data is now persistent!" << endl; outFile.close(); // Close after writing cout << "Data written successfully." << endl; } else { cout << "Error: Could not open file for writing." << endl; } // --- READING FROM A FILE --- ifstream inFile(fileName); string line; if (inFile.is_open()) { cout << "\nReading contents of " << fileName << ":" << endl; while (getline(inFile, line)) { // Read line by line cout << line << endl; } inFile.close(); } else { cout << "Error: Could not open file for reading." << endl; } return 0; }
Text Files (.txt, .csv): Data is stored as a sequence of characters (ASCII/UTF-8). Numbers like 1234 are stored as the characters '1', '2', '3', '4'. These are easy for humans to read but take up more space and require conversion.
Binary Files (.dat, .bin): Data is stored exactly as it appears in memory. The number 1234 is stored as its 4-byte integer representation.
Theory: Binary files are faster and smaller because no conversion to text is needed. However, they are not human-readable and can be "Endians-dependent" (meaning a binary file created on one type of CPU might not work on another).
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION