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

neversaint picture neversaint · Aug 4, 2009 · Viewed 10.4k times · Source

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

Answer

GManNickG picture GManNickG · Aug 4, 2009

If the reason you need to "go back again" is because you cannot continue without the size, try re-ordering your setup.

That is, read through the file, storing each line in a std::vector<string> or something. Then you have the size, along with the lines in the file:

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

Here is a solution without the container:

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

Though I doubt that's the most efficient way. The benefit of this method was the ability to store the lines in memory as you went.