int main()
{
ifstream file("myfile.txt");
if(!file.is_open())
{
cerr << "Could not open the file!";
return -1;
}
file.seekg(0, file.end);
while(file.tellg() > 0)
{
file.seekg(file.tellg() - 1, file.beg);
cout << static_cast<char>(file.get());
}
return 0;
}
However, if I comment out the file.get() operation, the loop works as intended.
I don't understand how the file.get() and file.tellg() are related, and how the file.seekg() fails to bring the cursor back of one position when file.get() is involved.
get() reads and moves the file position. Tell does not move the position. Tell is usually used not to get the file data but to get the current position: its more often used to find the size of the file (seek end, tell gives filesize) or for binary file work (where I am + sizeof(a record) * 10 or something).
honestly its probably a lot easier to read the whole thing into a vector of char or a giant string and iterate over it backwards than to do all this file position work. Unless its too big (over 4 GB on most modern machines, can be 50+ gb on a gaming pc with 64 GB ram etc, its tied to ram size what 'big' means).
So basically my seekg() call moves the pointer back of one position, and the get() moves it forward of one position, therefore the tellg() will never really reach 0.