Search code examples
c++linuxunixline-numbers

Most Compact Way to Count Number of Lines in a File in C++


What's the most compact way to compute the number of lines of a file? I need this information to create/initialize a matrix data structure.

Later I have to go through the file again and store the information inside a matrix.

Update: Based on Dave Gamble's. But why this doesn't compile? Note that the file could be very large. So I try to avoid using container to save memory.

#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;
}

Solution

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

    Answer in c. That kind of compact?