Reading from a file with fstream

In this snippet, we look at reading contents of a text file with the fstream library. The fstream, file stream, library provides the ifstream function for reading in files. Similarly, we can use the function getline() from the string library to returns individual lines from the file. Let's see a demonstration below:

Suppose we have a sample.txt file in the current directory with the following contents

$ ls
sample.txt    main.cpp
$ cat sample.txt 
This is a sample file
Reading it in C++
    

The following piece of code will read the contents with C++

#include <fstream>
#include <iostream>
#include <string>
        
int main() {

    // Open a given file
    std::ifstream my_file("sample.txt");
    std::string line;

    // reading lines
    if (my_file.is_open()) {
        while (std::getline(my_file, line)) {
            std::cout << line << "\n";
        }
    } else { std::cout << "File cannot be opened"; }

    // Close file
    my_file.close();
}

Compiling and running the code

$ g++ main.cpp -std=c++17 -o reading_from_file
$ ./reading_from_file
This is a sample file
Reading it in C++