File Handling in C++
File handling in C++ allows programs to read from and write to files. This is done using the
standard C++ library <fstream>, which provides three main classes:
File Stream Classes:
Class Purpose
ifstream Input file stream (for reading files)
ofstream Output file stream (for writing files)
fstream File stream for both input and output
Example 1: Writing to a File:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt"); // Create and open a file
if (file.is_open()) {
file << "Hello, world!\n";
file << "This is a file handling example.";
file.close(); // Always close the file
} else {
cout << "Unable to open file for writing.\n";
}
return 0;
}
Output:
Example 2: Reading from a File:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt"); // Open the file to read
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << "Unable to open file for reading.\n";
}
return 0;
}
Example 3: Take Input from User and Store in a File
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string data;
ofstream file("userdata.txt"); // Create or open the file for writing
if (file.is_open()) {
cout << "Enter your name: ";
getline(cin, data); // Get full line including spaces
file << "Name: " << data << endl;
cout << "Enter your age: ";
getline(cin, data);
file << "Age: " << data << endl;
cout << "Enter your address: ";
getline(cin, data);
file << "Address: " << data << endl;
file.close(); // Close the file
cout << "Data successfully saved to 'userdata.txt'." << endl;
} else {
cout << "Error opening file!" << endl;
}
return 0;
}
Output: