If I have a boost::filesystem::path
object, how can I get the line count of this file?
I need to compare the line counts of two files as a precondition check.
If I have a boost::filesystem::path
object, how can I get the line count of this file?
I need to compare the line counts of two files as a precondition check.
You can do something like this:
std::ifstream file(path.c_str());
// Number of lines in the file
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n');
Where path
is a boost::filesystem::path
. This will count the number of \n
in the file so you need to pay attention if there is a \n
at the end of the file to get the right number of lines.
You can use ifstream and getline to read file by line, and count it.
std::ifstream filein("aaa.txt");
int count = 0;
std::string line;
while (std::getline(filein, line))
{
count++;
}
std::cout << "file line count is " << count;
With stringstream, I advise to use intermediate string otherwise the streamstring will be consumed during the count and the iterator will not be at the beginning of the string for next getline.
string s = string("1\n2\n3\nlast");
stringstream sstream(s);
int nbOfLines = std::count(s.begin(), s.end(), '\n');
cout << "Nb of lines is: " << nbOfLines << endl;
Result:
Nb of lines is: 3
You can do getline from the beginning.
Or, for better performances (less copy), seek back to the beginning
int nbOfLines = std::count(std::istreambuf_iterator<char>sstream),std::istreambuf_iterator<char>(), '\n');
sstream.seekg(0, ios_base::beg);