File I O - Kamills-12/2143-OOP GitHub Wiki
File I/O (Input/Output) lets your program read data from and write data to files on your system.
In C++, it’s done with the <fstream>
library using three main classes:
Class | Use |
---|---|
ifstream |
Read from files |
ofstream |
Write to files |
fstream |
Do both (read + write) |
#include <fstream>
#include <iostream>
using namespace std;
## Write to a file
ofstream outfile("output.txt"); // creates or overwrites the file
outfile << "Hello, file!" << endl;
outfile << 123 << endl;
outfile.close();
## Read from a file
ifstream infile("data.txt");
string word;
while (infile >> word) {
cout << "Read: " << word << endl;
}
infile.close();
## Check if file opened
ifstream file("data.txt");
if (!file.is_open()) {
cout << "Error: file didn't open." << endl;
}