Lesson 36 of 45
C++Lesson 36: File I/O Streams
12 min
Course progress80%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 36 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
Reading from and writing to files in C++ is performed through the <fstream> library, which provides std::ifstream, std::ofstream, and std::fstream.
#include <fstream>
int main() {
std::ofstream out(\"data.txt\");
if (!out) {
std::cerr << \"Failed to open file for writing\
\";
return 1;
}
out << \"Header,Value\
\";
for (int i = 0; i < 5; ++i) {
out << i << \",\" << i * i << '\
';
}
// out is closed automatically when it goes out of scope
return 0;
}
#include <fstream>
#include <vector>
int main() {
std::ifstream in(\"data.bin\", std::ios::binary);
if (!in) {
std::cerr << \"Cannot open file\
\";
return 1;
}
// Determine file size
in.seekg(0, std::ios::end);
std::size_t size = in.tellg();
in.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
in.read(buffer.data(), size);
std::cout << \"Read \" << size << \" bytes\
\";
return 0;
}
Tip: Use
std::filesystem::existsto check file existence before opening.
<Alert type="warning">Always verify stream state (if (!stream)) before reading or writing to catch I/O errors early.