How can I count lines using the standard classes, fstream and ifstream?
kernel methods following @Abhay
A complete code I've done :
size_t count_line(istream &is)
{
// skip when bad
if( is.bad() ) return 0;
// save state
std::istream::iostate state_backup = is.rdstate();
// clear state
is.clear();
std::istream::streampos pos_backup = is.tellg();
is.seekg(0);
size_t line_cnt;
size_t lf_cnt = std::count(std::istreambuf_iterator(is), std::istreambuf_iterator(), '\n');
line_cnt = lf_cnt;
// if the file is not end with '\n' , then line_cnt should plus 1
is.unget();
if( is.get() != '\n' ) { ++line_cnt ; }
// recover state
is.clear() ; // previous reading may set eofbit
is.seekg(pos_backup);
is.setstate(state_backup);
return line_cnt;
}
it will not change the origin file stream state and including '\n'-miss situation processing for the last line.