Reading Files with ifstream
Read text and data.
What Is ifstream?
std::ifstream (input file stream) reads data from files. It behaves like std::cin but its source is a file on disk.
- Defined in
<fstream>. - Opens a file by name in its constructor.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("demo.txt") << "hello\n";
std::ifstream in("demo.txt");
std::string word;
in >> word;
std::cout << word << '\n';
return 0;
}Opening a File
Construct an ifstream with a filename, then check with is_open() whether the file was found.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("data.txt") << "42\n";
std::ifstream in("data.txt");
std::cout << (in.is_open() ? "opened" : "failed") << '\n';
return 0;
}All lessons in this course
- Reading Files with ifstream
- Writing Files with ofstream
- Binary File I/O
- Error Handling and State