C++ Get Total File Line Number

2019-01-24 15:09发布

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

5条回答
叼着烟拽天下
2楼-- · 2019-01-24 15:36

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;
查看更多
放我归山
3楼-- · 2019-01-24 15:43

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;
查看更多
Rolldiameter
4楼-- · 2019-01-24 15:44

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;
查看更多
孤傲高冷的网名
5楼-- · 2019-01-24 16:02

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');
查看更多
Juvenile、少年°
6楼-- · 2019-01-24 16:02

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

查看更多
登录 后发表回答