Thursday, July 24, 2014

Line counting in c++

Counting lines is not always the same as counting the newline character:

// count lines of a file
uint countlines(std::string fn) {
    std::ifstream in_file(fn);
    uint nlines =  (uint) std::count(std::istreambuf_iterator<char>(in_file), std::istreambuf_iterator<char>(), '\n');

    // nlines needs be corrected when the last line is not ended with a newline
    in_file.seekg(-1, in_file.end);
    unsigned char lastchar = in_file.get();
    if(lastchar != '\n') {

    return nlines;

If you use vim, depending on your setup, it might add a newline to your last line automatically, and it would appear the above correction is not needed.