Search code examples
c++boostboost-filesystem

File Line count using boost


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.


Solution

  • 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.