How to Read a File

beginner c++11 files

To open a file for reading in C++ we use std::ifstream (input file stream). Reading files is done with the std::ifstream object and the right shift operator(>>), similar to creating a file.

#include <fstream>
#include <iostream>

int main() {
  std::string filename{"file_with_single_number.txt"};
  std::ifstream input{filename};

  if (!input.is_open()) {
    std::cerr << "Couldn't read file: " << filename << "\n";
    return 1; 
  }

  int number = 0;
  input >> number;
  
  std::cout << "The number is " << number << ".\n";
}


Where the file file_with_single_number.txt is:

42

Read All Lines of a File

We can of course read all the lines of any given file one by one if we’d like. To read lines from a file we call std::getline which works with any kind of input stream, including file streams.

#include <fstream>
#include <iostream>
#include <vector>
#include <utility>

int main() {
  std::string filename{"file_with_multiple_lines.txt"};
  std::ifstream input{filename};

  if (!input.is_open()) {
    std::cerr << "Couldn't read file: " << filename << "\n";
    return 1; 
  }

  std::vector<std::string> lines;
  for (std::string line; std::getline(input, line);) {
    // Move the value of line into lines
    lines.push_back(std::move(line)); 
  }

  for (const auto& line : lines) {
    std::cout << line << "\n";
  }
}


Where the file file_with_multiple_lines.txt is:

The answer
to life
the universe
and everything

is

42.


For more C++ By Example, click here.