I have a function in my production code. The idea is that you are trying to read the last line, trying to find and read. Look here please.
bool readLastLine(std::string const& filename, std::string& lastLine) { std::ifstream in(filename.c_str(),std::ifstream::binary); if(!in) return false; in.seekg(0, std::ifstream::end); const std::streamoff len = in.tellg(); //empty file if(len == 0) { lastLine = ""; return true; } int buf_size = 128; std::vector<char> buf; while(in) { if(buf_size > len) { buf_size = len; } buf.resize(buf_size); in.seekg(0 - buf_size, std::ifstream::end); in.read(&buf[0],buf_size); //all content is in the buffer or we already have the complete last line if(len == buf_size || std::count(buf.begin(), buf.end(), '\n') > 1) { break; } //try enlarge the buffer buf_size *= 2; } //find the second line seperator from the end if any auto i = std::find(++buf.rbegin(),buf.rend(), '\n'); lastLine.assign(i == buf.rend() ? buf.begin() : buf.begin() + std::distance(i, buf.rend()), buf.begin() + buf_size); return true; }
source share