C++
File I/O
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.
Exercise 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.
Show example 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;
}
Test yourself
-
Which class saves tasks to a file?
std::ofstream out("tasks.txt");
- std::ifstream
- std::ofstream
- std::vector
- std::cout
Show answer
std::ofstream — std::ofstream is used to write to a file.
-
Read from a file
std::____ in("tasks.txt");
Show answer
std::ifstream in("tasks.txt");
-
Match each piece to its role
- std::ofstream
- Writing to file
- std::ifstream
- Reading from file
- out << t.title
- Writing title
- while (in >> ...)
- Loop reading
Next lesson: Putting it together