の合計ファイル行数を取得するために使用できる関数はありますか、それともループC++
で手動で行う必要がありますか?for
#include <iostream>
#include <ifstream>
ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?
}
text.txt
line1
line2
line3
I'd do like this :
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
++lines_count;
Or simply,
#include<algorithm>
#include<iterator>
//...
lines_count=std::count(std::istreambuf_iterator<char>(aFile),
std::istreambuf_iterator<char>(), '\n');
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".