C++ Get Total File Line Number

2019-01-24 15:10发布

问题:

Is there a function I can use to get total file line number in C++, or does it have to be manually done by for loop?

#include <iostream>
#include <ifstream>

ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?

}

text.txt

line1
line2
line3

回答1:

There is no such function. Counting can be done by reading whole lines

std::ifstream f("text.txt");
std::string line;
for (int i = 0; std::getline(f, line); ++i)
    ;

or by reading character-wise and checking for linefeed

std::ifstream f("text.txt");
char c;
int i = 0;
while (f.get(c))
    if (c == '\n')
        ++i;


回答2:

I'd do like this :

   ifstream aFile ("text.txt");   
   std::size_t lines_count =0;
   std::string line;
   while (std::getline(aFile , line))
        ++lines_count;

Or simply,

  #include<algorithm>
  #include<iterator>
  //...
  lines_count=std::count(std::istreambuf_iterator<char>(aFile), 
             std::istreambuf_iterator<char>(), '\n');


回答3:

I fear you need to write it by yourself like this:

int number_of_lines = 0;
 std::string line;
 while (std::getline(myfile, line))
        ++number_of_lines;

 std::cout << "Number of lines in text file: " << number_of_lines;


回答4:

Have a counter, initialized to zero. Read the lines, one by one, while increasing the counter (the actual contents of the line is not interesting and can be discarded). When done, and there was no error, the counter is the number of lines.

Or you can read all of the file into memory, and count the newlines in the big blob of text "data".



回答5:

Fast way then above solutions like P0W one save 3-4 seconds per 100mb

std::ifstream myfile("example.txt");

// new lines will be skipped unless we stop it from happening:    
myfile.unsetf(std::ios_base::skipws);

// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
    std::istream_iterator<char>(myfile),
    std::istream_iterator<char>(), 
    '\n');

std::cout << "Lines: " << line_count << "\n";
return 0;