Is there a function I can use to get total file line number in C++
, or does it have to be manually done by for
loop?
#include <iostream>
#include <ifstream>
ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?
}
text.txt
line1
line2
line3
There is no such function. Counting can be done by reading whole lines
or by reading character-wise and checking for linefeed
Fast way then above solutions like P0W one save 3-4 seconds per 100mb
I fear you need to write it by yourself like this:
I'd do like this :
Or simply,
Have a counter, initialized to zero. Read the lines, one by one, while increasing the counter (the actual contents of the line is not interesting and can be discarded). When done, and there was no error, the counter is the number of lines.
Or you can read all of the file into memory, and count the newlines in the big blob of text "data".