最简洁的方法来计算C++文件中的行数

nev*_*int 3 c++ unix linux line-numbers

计算文件行数最紧凑的方法是什么?我需要这些信息来创建/初始化矩阵数据结构.

稍后我必须再次浏览文件并将信息存储在矩阵中.

更新:基于Dave Gamble的.但为什么这不编译?请注意,该文件可能非常大.所以我尽量避免使用容器来节省内存.

#include <iostream>      
#include <vector>        
#include <fstream>       
#include <sstream>       
using namespace std;     


int main  ( int arg_count, char *arg_vec[] ) {
    if (arg_count !=2 ) {
        cerr << "expected one argument" << endl;
        return EXIT_FAILURE;      
    }

    string line;
    ifstream myfile (arg_vec[1]);

    FILE *f=fopen(myfile,"rb");
    int c=0,b;
    while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;
    fseek(f,0,SEEK_SET);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 10

如果您需要"再次返回"的原因是因为没有尺寸而无法继续,请尝试重新订购您的设置.

也就是说,通读文件,将每行存储在一个std::vector<string>或多个东西中.然后你有大小,以及文件中的行:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main(void)
{
    std::fstream file("main.cpp");
    std::vector<std::string> fileData;

    // read in each line
    std::string dummy;
    while (getline(file, dummy))
    {
        fileData.push_back(dummy);
    }

    // and size is available, along with the file
    // being in memory (faster than hard drive)
    size_t fileLines = fileData.size();

    std::cout << "Number of lines: " << fileLines << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这是一个没有容器的解决方案:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main(void)
{
    std::fstream file("main.cpp");
    size_t fileLines = 0;    

    // read in each line
    std::string dummy;
    while (getline(file, dummy))
    {
        ++fileLines;
    }

    std::cout << "Number of lines: " << fileLines << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

虽然我怀疑这是最有效的方式.这种方法的好处是能够在你去的时候将行存储在内存中.

  • I +真的很喜欢当我能告诉别人实际测试代码的时候,因为源文件的名称作为输入:D:D (3认同)

Eva*_*ran 10

我想这可能会这样做......

std::ifstream file(f);
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n') + 1;
Run Code Online (Sandbox Code Playgroud)


Dav*_*ble 6

FILE *f=fopen(filename,"rb");

int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET);
Run Code Online (Sandbox Code Playgroud)

答案c.那种紧凑?

  • `int c = 0; while(!fscanf(f,"%*[^ \n]%*c"))c ++; fseek(f,0,SEEK_SET)` (4认同)
  • 感激我离开了?1:0.没有,它工作正常.我在那里救了4个字符;) (2认同)