File Handling
File Handling
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:
Class Purpose
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;
}
if (file.is_open()) {
cout << "Enter your name: ";
getline(cin, data); // Get full line including spaces
file << "Name: " << data << endl;
return 0;
}
Output: