How to Read a File in C++

Reading a file in C++ is almost identical to how it’s done C.

#include <iostream>
#include <fstream>
int main()
{
  std::ifstream in("test.cpp");

  std::string line;
  auto num = 0;
  while (std::getline(in, line)) {
    num++;
    std::cout << num << ": " << line << std::endl;
  }

  in.close();

  return 0;
}

First we load the content of a file into a filestream. Next we iterate over each line, putting that into a string variable called line.

For each line in the file we print out the line prefixed with a line number to stdout.

And finally we close the filestream, and exit the program

Related Posts