Reading and Writing a File in C++
C++ provides a powerful set of file handling functions through the <fstream>
header to:
- Write data to a file using
ofstream
- Read data from a file using
ifstream
- Do both using
fstream
π§ Step-by-Step Process
1. Include the Required Header
#include <fstream>
2. Create a File Stream Object
- Use
ofstream
for writing - Use
ifstream
for reading - Use
fstream
for both
βοΈ Writing to a File
β Example: Writing Text to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("myfile.txt"); // Open file in write mode
if (outFile.is_open()) {
outFile << "Hello BCA Students!\n";
outFile << "This is C++ file writing example.\n";
outFile.close(); // Close file
cout << "Data written successfully!" << endl;
} else {
cout << "Failed to open the file." << endl;
}
return 0;
}
π What It Does:
- Opens (or creates)
myfile.txt
- Writes two lines to the file
- Closes the file
π Reading from a File
β Example: Reading Text from a File Line by Line
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("myfile.txt"); // Open file in read mode
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close(); // Close file
} else {
cout << "Unable to open the file." << endl;
}
return 0;
}
π What It Does:
- Opens
myfile.txt
- Reads each line using
getline()
- Prints the content to the console
π‘ Reading and Writing Other Data Types
You can also read and write integers, floats, characters, etc.
β Writing Numbers
ofstream file("numbers.txt");
int a = 100;
float b = 25.75;
file << a << " " << b;
file.close();
β Reading Numbers
ifstream file("numbers.txt");
int x;
float y;
file >> x >> y;
cout << "x = " << x << ", y = " << y;
file.close();
π¦ Reading and Writing Using fstream
(Both Read & Write)
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("data.txt", ios::out); // write mode
file << "BCA File Handling Example\n";
file.close();
file.open("data.txt", ios::in); // read mode
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
return 0;
}
π Summary Table
Operation | Stream Class | Function Used |
---|---|---|
Writing to file | ofstream | << |
Reading from file | ifstream | >> or getline() |
Both read & write | fstream | << , >> |
Close a file | Any stream | .close() |
βBest Practices
- Always check if the file is open before reading or writing.
- Always close the file after operations.
- Handle possible file errors using
is_open()
or error messages.