What is the most compact way to calculate the number of lines of a file? I need this information to create / initialize a matrix data structure.
Later I need to view the file again and save the information inside the matrix.
Update: Based on Dave Gamble's. But why doesn't it compile? Please note that the file can be very large. Therefore, I try to avoid using a 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;
}
source
share