How to Read a File in C++

Tue, Oct 4, 2016

Read in 1 minutes

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

See Also

How to Read a File in C#

Tue, Nov 8, 2016

Read more →

How to Read a File in Lua

Fri, Oct 28, 2016

Read more →

How to parse JSON in C++

Fri, Sep 16, 2016

Read more →

How to read a file in Java

Tue, Sep 13, 2016

Read more →

How to use SQLite in C++

Tue, Jul 9, 2019

Read more →