File I/O
Programming
This program demonstrates file input/output operations using std::ofstream for writing and std::ifstream for reading.
Implementation
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile("example.txt");
outfile << "This is a test file." << std::endl;
outfile.close();
std::ifstream infile("example.txt");
std::string line;
std::getline(infile, line);
std::cout << "Read from file: " << line << std::endl;
infile.close();
return 0;
} Key Concepts
- ofstream: Output file stream for writing to files
- ifstream: Input file stream for reading from files
- open(): Opens a file (automatic with constructor)
- close(): Closes the file and flushes buffers
- getline(): Reads a line from the file into a string
- File streams use the same operators (
<<and>>) as console I/O
Output
Read from file: This is a test file.