File I/O
- C++ course
- Intermediate
- Lesson 115/116
- 6 min
Save and load data to/from files.
File I/O: save and load
In this lesson we save tasks to a file and load them back. We write with std::ofstream and read with std::ifstream.
Example: std::ofstream out("tasks.txt"); out << t.title << " " << t.done;. This writes a task's title and status to a file. To read back: std::ifstream in("tasks.txt"); in >> title >> done;. You can write and read multiple tasks in a loop. We take the Task class and printItem template from previous lessons and add file I/O on top.
Save and load in a loop
To save multiple tasks you use a for loop. When loading back, a while (in >> title >> done) loop reads until the end of the file.
Example: for (const auto& t : tasks) { out << t.title << " " << t.done << "\n"; }. This writes each task on one line. When reading back: while (in >> title >> done) { count++; } increments the counter on each successful read. >> extracts whitespace-separated data; \n moves to the next read. This pattern is the basis of save-load operations.
Practice Save tasks to a file and load them back
After the Task class and printItem template in the starting code, create a std::vector<Task> in main. Add two tasks (Homework, Sport). Save them to tasks.txt with std::ofstream. Load back with std::ifstream, count and print with std::cout.
Starter code
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
class Task {
public:
std::string title;
bool done;
Task(std::string t) : title(t), done(false) {}
};
template <typename T>
void printItem(const T& item) {
std::cout << item;
}
int main() {
// Add two tasks to a vector, save to file, load back and count
return 0;
}Sample solution
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
class Task {
public:
std::string title;
bool done;
Task(std::string t) : title(t), done(false) {}
};
template <typename T>
void printItem(const T& item) {
std::cout << item;
}
int main() {
std::vector<Task> tasks;
tasks.push_back(Task("Homework"));
tasks.push_back(Task("Sport"));
std::ofstream out("tasks.txt");
for (const auto& t : tasks) {
out << t.title << " " << t.done << "\n";
}
out.close();
std::ifstream in("tasks.txt");
std::string title;
bool done;
int c = 0;
while (in >> title >> done) {
c++;
}
std::cout << c;
return 0;
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which class saves tasks to a file?
std::ofstream out("tasks.txt");- std::ifstream
- std::ofstream Correct answer
- std::vector
- std::cout
Explanation: std::ofstream is used to write to a file.
2 Read from a file
std::____ in("tasks.txt");
std::ifstream in("tasks.txt");
Explanation: std::ifstream reads from a file.
3 Match each piece to its role
| Term | Meaning |
|---|---|
std::ofstream |
Writing to file |
std::ifstream |
Reading from file |
out << t.title |
Writing title |
while (in >> ...) |
Loop reading |