-1

I need to read the last line of file that is growing while some calculations are made. At the beginning there is no problem because the file is small, but when the file gets bigger the reading process is to slow.

while(!file.eof()){
 if ((std::getline(file,line))){
   std::istringstream iss(line);
   std::istream_iterator<double> it(iss), end;
   std::vector<double> v(it, end);
   std::copy(v.begin(), v.end(), arr);
   v.clear();
   line.clear();
  }
}

What is a more efficient way to read the last line of a file with out reading all the file until the end is reach?

2 Answers2

0

use seekg() to jump to the end of file, and read backward - something like this

if(fs.is_open())
  {
    fs.seekg(-1, std::ios_base::end);
    if(fs.peek() == '\n')
    {
      fs.seekg(-1, std::ios_base::cur);
      int i = fs.tellg();
      for(i;i > 0; i--)
      {
        if(fs.peek() == '\n')
        {
          //Found
          fs.get();
          break;
        }
        fs.seekg(i, std::ios_base::beg);
      }
    }
    std::string lastline;
    getline(fs, lastline);
Deb S
  • 491
  • 4
  • 14
0

Use this algorithm:

  • Seek until the end of the file.
  • Copy in reverse until newline is reached (skip the newline if file ends in it). EDIT: This step is actually a bit tricky with streams. Memory mapping would make this easier, however keep in mind that there is no standard API for memory mapping.
  • The copy is now the last line in reverse.

You could just reverse search for the newline and copy in forward direction, or just reverse the inverted line, or you could copy into the front of a double ended queue so that the line is reversed while copying, but perhaps fastest might be to keep it reversed and process it with reverse iterators, depending on what you intend to do with the line.

eerorika
  • 181,943
  • 10
  • 144
  • 256