capypad
0 day streak
cpp / beginner
Snippet

Basic File Input and Output

C++ provides fstream for file operations. ofstream creates and writes to files, while ifstream reads from files. Always check if a file opened successfully using is_open(), and close files when done to free system resources.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <string>
 
int main() {
std::ofstream outFile("data.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl;
outFile << "C++ file handling" << std::endl;
outFile.close();
std::cout << "File written successfully!" << std::endl;
}
std::ifstream inFile("data.txt");
std::string line;
if (inFile.is_open()) {
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
}
return 0;
}
Breakdown
1
std::ofstream outFile("data.txt");
Creates an output file stream to write to 'data.txt'
2
outFile.is_open()
Checks if the file was successfully opened
3
outFile << "Hello, World!"
Writes text to the file using the stream operator
4
std::ifstream inFile("data.txt");
Creates an input file stream to read from 'data.txt'
5
std::getline(inFile, line)
Reads one line at a time from the file into the string