C/C++ Arena

Step 4 of 6

Reading files with ifstream

std::ifstream opens a file as an input stream. Everything you know from std::cin and std::getline applies:

std::ifstream in("roster.txt");
if (!in) { /* couldn't open it */ }
std::string line;
while (std::getline(in, line)) { ... }

There's no close() to forget: the destructor closes the file when in goes out of scope. That's RAII again.

Your turn: write std::optional<std::vector<std::string>> read_lines(const std::string& path) returning the file's lines without their newlines, skipping empty lines, or std::nullopt if the file can't be opened.

Previous: Building strings with ostringstream Next: Writing files with ofstream