SergeantPenguin
SergeantPenguin

Reputation: 873

fstream and seekg not operating as intended

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

int main(){

    fstream input("EX17.39file.txt", fstream::ate | fstream::out | fstream::in);

    if(!input){
        cout << "Failed to open file. Exiting." << endl;
        return EXIT_FAILURE;
    }

    auto end_mark = input.tellp();
    input.seekg(0, fstream::beg);

    for(string line; getline(input, line);){

        auto read_mark = input.tellg();

        input.seekp(0, fstream::end);
        input.seekg(read_mark);

        char c;
        while(input >> c)
        cout << c << " ";

    }


}

All the inside of the while loop really does is move from the current position to the end, and then back to the current position. Then it outputs each character left in the stream. Except for an input file of something like:

abcd
efg
//newline

My output is

f g

I find it odd that e got missed. If I move the part of the loop which outputs the rest of the stream before the input.seekp(0, fstream::end); command, i.e.

for(string line; getline(input, line);){

        auto read_mark = input.tellg();

        char c;
        while(input >> c)
        cout << c << " ";

        input.clear();
        cout << endl;

        input.seekp(0, fstream::end);
        input.seekg(read_mark);     

}

then e f g gets output like normal. So when the stream gets placed to the end, and then back to its original position, for some reason it isn't placed in the correct position and misses e?

If I change everything from an fstream to a stringstream:

stringstream input("abcd\nefg\n", fstream::ate | fstream::out | fstream::in);

Then it outputs like I expect.

Why is seekg(read_mark) not bringing it back to its original position? (mingw64 gcc 5.2.0).

Edit: input.tellg() before the move and input.tellg() after the move both output the same value of 7.

Upvotes: 2

Views: 250

Answers (0)

Related Questions