In C++, File Input and Output refers to the program’s operations for reading (input) and writing (output) data to and from files on disk. This is a crucial feature in many practical applications, such as:
-
Reading configuration files
-
Saving user data (e.g., game saves, score records)
-
Importing/exporting text or data files
-
Logging, etc.
🎯 1. What Library is Used for File Operations in C++?
The C++ Standard Library provides the <span><fstream></span> header file, which includes classes for file input and output. It is a tool specifically designed for file operations in the C++ Standard Library, based on the concept of streams, similar to <span>cin/cout</span>.
✅ 2. Three Core Classes in <span><fstream></span>
|
Class Name |
Function |
Description |
|---|---|---|
|
|
Input File Stream |
Used to read data from a file (input), equivalent to |
|
|
Output File Stream |
Used to write data to a file (output), equivalent to |
|
|
Input & Output File Stream |
Can read from and write to a file, used flexibly |
🧠 All of them inherit from the stream classes in
<span>iostream</span>, so their usage is similar to<span>cin/cout</span>, but the operation target is files instead of the console.
📂 3. Basic Steps for File Operations (Using <span>ofstream</span> and <span>ifstream</span> as Examples)
1. Include Header Files
#include <fstream> // File stream operations
#include <iostream> // Optional, for console output prompts
using namespace std;
2. Create File Stream Objects
-
Write to file →
<span>ofstream outFile("filename.txt");</span> -
Read from file →
<span>ifstream inFile("filename.txt");</span> -
Read and write to file →
<span>fstream file("filename.txt", mode);</span>
3. Open the File (Usually Automatically Done in the Constructor)
You can also manually call the <span>.open("filename")</span> method.
4. Operate on the File: Write or Read Data
-
Writing: Use the
<span><<</span>operator, just like<span>cout</span> -
Reading: Use the
<span>>></span>operator, just like<span>cin</span>
5. Close the File (Usually Automatically Done in the Destructor, but Can Also Be Manually Called with <span>.close()</span>)
✅ 4. 🔧 Example 1: Using <span>ofstream</span> to Write to a File (Output to File)
📝 Function: Write Some Text to the File <span>example.txt</span>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// Create an ofstream object, open the file "example.txt" (create if it does not exist)
ofstream outFile("example.txt"); // Default mode is ios::out (write)
if (!outFile) {
cerr << "Unable to open file for writing!" << endl;
return 1;
}
// Write data to the file (using <<, similar to cout)
outFile << "Hello, file writing!" << endl;
outFile << "This is the second line." << endl;
outFile << "C++ file operations are powerful!" << endl;
// Close the file (optional, automatically closed on destruction)
outFile.close();
cout << "Data has been successfully written to file example.txt" << endl;
return 0;
}
🔍 After Running:
-
The program will generate a
<span>example.txt</span>file in your project directory (or the directory where the executable is located) -
The file will contain three lines of text
✅ 5. 🔧 Example 2: Using <span>ifstream</span> to Read from a File (Input from File)
📝 Function: Read Content from the <span>example.txt</span> File and Display on Screen
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream inFile("example.txt"); // Open the file for reading
if (!inFile) {
cerr << "Unable to open file for reading! Please confirm if the file exists." << endl;
return 1;
}
string line;
cout << "File content is as follows:" << endl;
// Read file content line by line
while (getline(inFile, line)) { // getline is used to read a line (including spaces)
cout << line << endl;
}
inFile.close(); // Close the file
return 0;
}
🔍 Running Effect:
-
The program will read each line of content from
<span>example.txt</span>and print it to the console -
Used
<span>getline(inFile, line)</span>to read a line of text (can include spaces)
✅ 6. 🔧 Example 3: Using <span>fstream</span> to Read and Write to a File
If you want to open a file and both read and write, you can use <span>fstream</span> and specify the open mode.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// Open the file (create if it does not exist), mode for read and write (in | out)
fstream file("data.txt", ios::in | ios::out | ios::trunc);
if (!file) {
cerr << "Unable to open file!" << endl;
return 1;
}
// Write data
file << "This is the first line of written content." << endl;
file << "This is the second line." << endl;
// Move the file pointer to the beginning of the file, ready to read
file.seekg(0, ios::beg);
// Read the content just written
string line;
cout << "Reading file content:" << endl;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
return 0;
}
🧠
<span>seekg(0, ios::beg)</span><span> moves the </span><strong><span>read pointer to the beginning of the file</span></strong><span>, allowing you to read the content just written again.</span>
🧠 7. File Open Modes
When opening a file, you can specify different modes. Common modes are as follows (can be combined, such as <span>ios::in | ios::out</span>):
|
Mode |
Description |
|---|---|
|
|
Open the file for reading (input) |
|
|
Open the file for writing (output), overwrites the original file |
|
|
Append mode, content written will be added to the end of the file (not overwrite) |
|
|
Open the file and position to the end of the file (usually combined with other modes) |
|
|
If the file already exists, clears the file content (default used with |
|
|
Open the file in binary mode (non-text mode) |
For example:
<span>ofstream file("data.txt", ios::out | ios::app);</span>→ Write, but append to the end of the file
<span>ifstream file("data.txt", ios::in);</span>→ Open in read-only mode
✅ 8. Summary: Key Points of C++ File Input and Output (fstream)
|
Function |
Class |
Description |
Common Operations |
|---|---|---|---|
|
Write to File |
|
Output to file (write) |
|
|
Read from File |
|
Read from file |
|
|
Read and Write to File |
|
Can read and write |
Combine as needed |
|
Open File |
Constructor or |
Specify file name and mode |
|
|
Close File |
|
Generally can be omitted (automatically closed on destruction) |
|
|
Read a Line (Including Spaces) |
|
Recommended for text reading |
|
|
File Open Modes |
|
Control the file opening method |
Used in combination, such as |