tellg() and get()

I have written a simple algorithm to read a text file backwards:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
    ifstream file("myfile.txt");

    if(!file.is_open())
    {
        cerr << "Could not open the file!";
        return -1;
    }

    file.seekg(0, file.end);

    int x = file.tellg();

    while(x--)
    {
        file.seekg(x, file.beg);

        cout << static_cast<char>(file.get());
    }

    return 0;
}


However, if I remove the variable x and just use file.tellg(), I get an infinite loop which only prints the very last character of the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.

Any clarifications?

Thanks in advance!
Last edited on
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).
Last edited on
get() reads and moves the file position


This is exactly what I wanted to know!

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.

Thanks ;)
Last edited on
Topic archived. No new replies allowed.