C++ 获取文件总行数

6

C++ 中是否有函数可以用来获取文件总行数,还是必须手动使用 for 循环来完成?

#include <iostream>
#include <ifstream>

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

}

text.txt

line1
line2
line3
7个回答

13

我会这样做:

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

或者简单地说,

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

1
在 "while (std::getline(aFile , line))" 中,line 是什么? - NewFile
6
赞成使用 std::count 变体函数。 - Some programmer dude
std::count变体有什么优势? - qed

10

没有这样的功能。可以通过读取整行来进行计数。

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

关于作用域的注意事项,变量i必须在for之外声明,如果您想在循环后访问它。
你可以逐个字符阅读并检查换行符。
std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
    if (c == '\n')
        ++i;

我在第二个函数中得到了0。 - NewFile
@NewFile 你说得对,operator>>()会跳过空格。谢谢提醒,已修复。 - Olaf Dietsche

2
我担心你需要自己按照以下方式编写它:

我害怕你需要像这样自己写:

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;

1

有一个计数器,初始化为零。逐行读取内容,同时增加计数器(实际行内容无关紧要且可丢弃)。完成后,如果没有错误,计数器就是行数。

或者你可以将整个文件读入内存,在文本“数据”中计算换行符以得到行数。


1

stackoverflow.com/a/19140230/9564035中的解决方案很好,但不能提供相同的输出。 如果您只想计算以'\n'结尾的行,请使用

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

如果您想计算未以'\n'(最后一行)结尾的行数,您应该使用getLine解决方案。
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
   ++lines_count;

请注意,如果您之前从文件中读取过内容,则需要将指针设置为文件开头,使用 file.seekg(std::ios_base::beg);

0

比如 P0W 的解决方案,比上述方案更快速,每 100mb 可以节省 3-4 秒。

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;

在我的实验中,使用 istreambuf_iterator 而不是 istream_iterator 使速度提高了5倍。 - gus3001

-1

只需复制并运行。

#include <stdio.h>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    fstream file;
    string filename = "sample input.txt";
    file.open(filename.c_str()); //read file as string 
    int lineNum = 0;
    string s;
    if (file.is_open())
    {
        while (file.good())
        {
            getline(file, s);
            lineNum++;
            cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
        }
        cout << "Total Line : " << lineNum << endl;
        file.close();
    }

    return 0;
}

明确要求点赞违反了SO的政策,你的帖子已被编辑以删除该部分。然而,如果你的回答建议使用#include <bits/stdc++.h>,你不太可能得到任何点赞。 - Adrian Mole
我不知道SO的政策。感谢您宝贵的反馈。 - Abdullah Al Masum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接