1

If I have a boost::filesystem::path object, how can I get the line count of this file?

I need to compare the line counts of two files as a precondition check.

Jonas Stein
  • 6,826
  • 7
  • 40
  • 72
qzcx
  • 361
  • 1
  • 12
  • Read every line and count them – Rogiel Sulzbach May 22 '14 at 14:42
  • There unfortunately isn't any way faster than reading the file and counting lines. How you do that is up to you. You can count the number of `'\n'` characters, the number of times `getline()` returns something, etc. – Cory Kramer May 22 '14 at 14:45
  • @Cyber although you can read a file counting lines /faster/: http://stackoverflow.com/questions/17925051/fast-textfile-reading-in-c/17925143#17925143 – sehe May 22 '14 at 20:48

3 Answers3

5

You can do something like this:

std::ifstream file(path.c_str());

// Number of lines in the file
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n');

Where path is a boost::filesystem::path. This will count the number of \n in the file so you need to pay attention if there is a \n at the end of the file to get the right number of lines.

Elie Génard
  • 1,673
  • 3
  • 21
  • 34
2

You can use ifstream and getline to read file by line, and count it.

std::ifstream filein("aaa.txt");
int count = 0;
std::string line; 
while (std::getline(filein, line))
{
    count++;
}
std::cout << "file line count is " << count;
Jerry YY Rain
  • 4,134
  • 7
  • 35
  • 52
0

With stringstream, I advise to use intermediate string otherwise the streamstring will be consumed during the count and the iterator will not be at the beginning of the string for next getline.

string s = string("1\n2\n3\nlast");
stringstream sstream(s);  
int nbOfLines = std::count(s.begin(), s.end(), '\n');
cout << "Nb of lines is: " << nbOfLines << endl;  

Result:

Nb of lines is: 3

You can do getline from the beginning.

Or, for better performances (less copy), seek back to the beginning

int nbOfLines = std::count(std::istreambuf_iterator<char>sstream),std::istreambuf_iterator<char>(), '\n');
sstream.seekg(0, ios_base::beg);
Nicosmik
  • 791
  • 1
  • 5
  • 7