There are numerous questions dealing with counting the number of lines in a file. I have successfully implemented this, using std::count
, as per suggested in this question.
My present challenge is that I need to have some robustness when dealing with the files -- some of these files might have a blank line at the end, other times it might not. Some of the files have UNIX line endings, other have Windows line endings.
I have tried looking for a '\n' at an offset of -1 from the end of the input stream, but this has not been successful. The code would look something along these lines:
std::ios::pos_type current_location = is_->tellg();
is_->seekg(0);
auto saved_flags = is_->flags();
uint64_t total_records(0);
total_records = std::count(std::istreambuf_iterator<char>(*is_),
std::istreambuf_iterator<char>(), '\n');
// Check that the last character before the end of the file is not a '\n'
is_->seekg(-1,std::ios_base::end);
if (is_->peek() == '\n')
total_records--;
// restore the saved position and flags
is_->seekg(current_location);
is_->flags(saved_flags);
return total_records ? ++total_records : 0;
However, this does not work -- the count is not decrmented by 1, so this function returns a count with 1 number too many records.
Obviously, this is a trivial problem if I can mandate that all files must have a trailing newline or must not have the trailing newline. I feel like allowing for both possibilities should not be that difficult, and that I am missing something obvious here.
UPDATE: Just as a matter of clarification, this is not a homework question. This is for a personal project that I have been working on.
Any help would be greatly appreciated.
Thanks- Shmuel