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

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


I think this might do it...

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


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.


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?