I'm trying to get last line of file, using logic described here Fastest way to read only last line of text file?, but I'm getting some strange anomaly:
score.seekg(-2, ios::cur);
resets my stream to the same character, so I get infinite loop. However, setting it to -3
works perfectly:
fstream score("high_scores.txt"); //open file
if(score.is_open()) //file exist
{
score.seekg(0, ios::end);
char tmp = '~';
while(tmp != '\n')
{
score.seekg(-3, ios::cur);
if((int)score.tellg() <= 0) //start of file is start of line
{
score.seekg(0);
break;
}
tmp = score.get();
cout << tmp << "-";
}
}
Again, the problem is - this code works only with seekg()
offset -3
, when, theoretically, it should work with -2
. Can this be explained somehow? The file contents are like this (newline at the end of file):
28 Mon Jul 10 16:11:24 2017
69 Mon Jul 10 16:11:47 2017
145 Mon Jul 10 16:53:09 2017
I'm using Windows, so now I understand why I need -3
offset from the end of file (to pass CR and LF bytes). But lets consider first char (from end).
28 Mon Jul 10 16:11:24 2017
So, stream gets to 7
. It extracts it, and moves to CR byte. If, then, in next loop iteration we offset it -3
, we will get 0
, but not 1
! But in reality, I'm getting 1
! And all works fine with -3
offset. That is the mystery for me. Can't get it out of my head.