malhobayyeb
malhobayyeb

Reputation: 2873

How to count lines of a file in C++?

How can I count lines using the standard classes, fstream and ifstream?

Upvotes: 43

Views: 136239

Answers (8)

fishshrimp鱼虾爆栈
fishshrimp鱼虾爆栈

Reputation: 141

kernel methods following @Abhay

A complete code I've done :

#include <fstream>

std::size_t count_line(std::istream &is) {
    // skip when is not open or got bad
    if (!is || is.bad()) { return 0; }
    // save state
    auto state_backup = is.rdstate();
    // clear state
    is.clear();
    auto pos_backup = is.tellg();

    is.seekg(0);
    size_t line_cnt;
    size_t lf_cnt = std::count(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), '\n');
    line_cnt = lf_cnt;
    // if the file is not end with '\n' , then line_cnt should plus 1
    // but we should check whether file empty firstly! or it will raise bug
    if (is.tellg() != 0) {
        is.unget();
        if (is.get() != '\n') { ++line_cnt; }
    }

    // recover state
    is.clear() ; // previous reading may set eofbit
    is.seekg(pos_backup);
    is.setstate(state_backup);

    return line_cnt;
}

it will not change the origin file stream state and including '\n'-miss situation processing for the last line.

Thanks @masoomyf for pointing my bug and I was too stupid to figure it out!

Upvotes: 3

Adem Budak
Adem Budak

Reputation: 65

This works for me:

  std::ifstream fin{"source.txt"};
  std::count(std::istream_iterator<char>(fin >> std::noskipws), {}, '\n');

Upvotes: 0

Maria
Maria

Reputation: 63

int aNumOfLines = 0;
ifstream aInputFile(iFileName); 

string aLineStr;
while (getline(aInputFile, aLineStr))
{
    if (!aLineStr.empty())
        aNumOfLines++;
}

return aNumOfLines;

Upvotes: 0

Billy ONeal
Billy ONeal

Reputation: 106530

This is the correct version of Craig W. Wright's answer:

int numLines = 0;
ifstream in("file.txt");
std::string unused;
while ( std::getline(in, unused) )
   ++numLines;

Upvotes: 13

John
John

Reputation: 13

Divide the file size by the average number of characters per line!

Upvotes: -14

Craig Wright
Craig Wright

Reputation: 1605


int numLines = 0;
ifstream in("file.txt");
//while ( ! in.eof() )
while ( in.good() )
{
   std::string line;
   std::getline(in, line);
   ++numLines;
}

There is a question of how you treat the very last line of the file if it does not end with a newline. Depending upon what you're doing you might want to count it and you might not. This code counts it.

See: http://www.cplusplus.com/reference/string/getline/

Upvotes: -3

Abhay
Abhay

Reputation: 7180

How about this :-

  std::ifstream inFile("file"); 
  std::count(std::istreambuf_iterator<char>(inFile), 
             std::istreambuf_iterator<char>(), '\n');

Upvotes: 131

Loki Astari
Loki Astari

Reputation: 264331

You read the file line by line. Count the number of lines you read.

Upvotes: 13

Related Questions