Introduction to Reading and Writing Files in CPP
#Introduction Reading Writing Files in CPP
Overview
Reading and writing files in C++ is a crucial part of programming when you need to store data permanently or retrieve existing data from storage. This is commonly used in applications such as text editors, configuration storage, logging systems, and data processing.
C++ provides the <fstream>
library which offers three main classes:
Class | Purpose |
---|---|
ifstream | Read data from files (input) |
ofstream | Write data to files (output) |
fstream | Read and write data from/to files |
You must include the <fstream>
header to use these classes.
#include <fstream>
This example demonstrates how to create and write data to a file named "data.txt".
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.txt"); // Open file for writing
if (outFile.is_open()) {
outFile << "Hello, this is a sample text." << endl;
outFile << "C++ makes file handling easy!" << endl;
outFile.close();
cout << "Data written to file successfully." << endl;
} else {
cout << "Error opening file for writing." << endl;
}
return 0;
}
Output (data.txt):
Hello, this is a sample text.
C++ makes file handling easy!
This example shows how to read data from the "data.txt" file created earlier.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("data.txt"); // Open file for reading
string line;
if (inFile.is_open()) {
cout << "Reading from file:\n";
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Error opening file for reading." << endl;
}
return 0;
}
Sample Output:
Reading from file:
Hello, this is a sample text.
C++ makes file handling easy!
Always call close()
to close the file after operations.
Check is_open()
before reading or writing.
Use getline()
for line-by-line reading.
Combine file open modes like ios::in | ios::out
when needed.
Reading and writing files in C++ is simple and powerful with the fstream
library. Mastering these operations allows developers to create applications that can store and retrieve data efficiently from the file system.