File Handling
C++ provides the fstream library for file input/output.
The main classes are ifstream (input), ofstream (output), and fstream (both).
Opening and Creating Files
Use the constructor or open() method. Specify the file name and mode.
Common modes: ios::out (write), ios::in (read), ios::app (append).
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, file!\n";
file << "C++ file handling is easy.\n";
file.close();
cout << "File created and written.\n";
}
return 0;
}
Try it Yourself โ