File Handling
C++ File Handling
Definition: File handling in C++ allows a program to store data permanently on a storage device (like a hard drive) rather than keeping it temporarily in RAM. By using files, your program's output can be saved, shared, and reopened even after the program has stopped running.
Why: File handling is a staple of beginner C++ curricula because it transitions students from "toy" programs into building functional software. Whether you are saving user settings, logging application errors, or processing large datasets, mastering the fstream library is essential for any real-world C++ application.
The fstream Library Classes
To work with files, you must include the <fstream> header file. This library provides three main classes, each designed for a specific type of file interaction:
| Class | Purpose | Analogy |
|---|---|---|
ofstream |
Output File Stream: Used to create files and write information to them. | Writing a letter and putting it in an envelope. |
ifstream |
Input File Stream: Used to read information from existing files. | Opening and reading a letter you received. |
fstream |
File Stream: A combination of both; can create, write, and read files. | A two-way notebook for both writing and reading. |
Example: Writing Data to a File
The following program demonstrates the basic "Open-Write-Close" workflow. It creates a file named sample.txt and writes a welcome message into it:
#include <iostream> #include <fstream> // Required for file operations using namespace std; int main() { // 1. Create and open a text file for writing ofstream myFile("sample.txt"); // 2. Write to the file (uses same syntax as cout) myFile << "Welcome to C++ File Handling!"; // 3. Close the file to save changes and free memory myFile.close(); cout << "File created and data written successfully." << endl; return 0; }
Common File Operation Steps
- Include
<fstream>: Always include the library at the top of your code. - Open the File: Use the constructor (as shown above) or the
.open()method. By default,ofstreamwill overwrite the file if it already exists. - Check for Errors: It is best practice to verify the file opened correctly using
if(myFile.is_open()). - Perform Operations: Use
<<to write orgetline()/>>to read. - Close the File: Always call
.close(). If you forget, you may lose data or prevent other programs from accessing the file.
Key Notes
- File Modes: You can control how a file is opened by passing a second argument. For example,
ios::app(append mode) allows you to add new text to the end of a file without deleting its current contents. - Path Management: If you only provide a filename (like
"sample.txt"), C++ looks for it in the same folder where your project is running. To access files elsewhere, you must provide the full file path. - Reading with
getline(): When reading from a file, usingmyFile >> variableonly reads until the first space. To read an entire line including spaces, use thegetline(myFile, lineVariable)function. - Resource Safety: File handling is where C++'s RAII (Resource Acquisition Is Initialization) principle shines—modern C++ often handles closing files automatically when the stream object goes out of scope, though manual closing remains a vital skill for beginners.
🏋️ Test Yourself With Exercises
Take our quiz on File Handling to test your knowledge.
Browse Quizzes »