std::ifstream
- C++ course
- Intermediate
- Lesson 88/116
- 5 min
Learn to read files with std::ifstream.
Reading with std::ifstream
std::ifstream opens a file for reading. It comes from the #include <fstream> header. You pull data out of the file with the >> operator.
In this lesson we learn to read from files. For working examples we first create the file with std::ofstream; we will study writing in the next lesson. Example: std::ifstream in("data.txt"); opens the file for reading. Then std::string word; in >> word; extracts the first word. When done, in.close(); closes the file.
Reading with the >> operator
The >> operator extracts whitespace-separated pieces from the file. std::string a, b; in >> a >> b; reads two words in sequence.
Each >> call reads up to the next whitespace and skips it. When the file ends, >> fails. That is why loops often use while (in >> word): it keeps looping while reading succeeds. The same operator reads numbers: int n; in >> n; extracts an integer into n.
Practice Read a word from the file and print it
The starting code creates a data.txt file with the content "Hello". Open it with std::ifstream, read one word with >> and print it with std::cout.
Starter code
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Prepare the file (writing is covered in the next lesson)
std::ofstream out("data.txt");
out << "Hello";
out.close();
// Read the file and print to screen
return 0;
}Sample solution
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream out("data.txt");
out << "Hello";
out.close();
std::ifstream in("data.txt");
std::string word;
in >> word;
std::cout << word;
return 0;
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does std::ifstream in("data.txt"); do?
std::ifstream in("data.txt");- Writes to the file
- Opens the file for reading Correct answer
- Deletes the file
- Copies the file
Explanation: std::ifstream opens the file for reading.
2 Specify the file name
std::ifstream in(____);
std::ifstream in("data.txt");
Explanation: The file name is given in double quotes.
3 Match each piece to its role
| Term | Meaning |
|---|---|
std::ifstream |
File reading |
>> |
Data extraction |
in.close() |
Closing the file |
#include <fstream> |
Header file |