are “seekp” & “seekg” interchangeable?

后端 未结 2 799
忘了有多久
忘了有多久 2020-12-05 23:50

Well I just noticed that by changing the position -in microsoft visual studio- through \"seekp\" I implicitelly also change the read-position, when handling files.

I

2条回答
  •  一整个雨季
    2020-12-06 00:33

    Update: So from all the comments and everything, it seems that for fstream, seekp and seekg use the same pointer. But for stringstream and probably other non-file based streams, they are separate.


    Original Post:

    Doesn't work for me on linux with g++ 4.7.2. They seem to be independent:

    #include 
    #include 
    
    int main(int, char**) {
        std::stringstream s("0123456789");
        std::cout << "put pointer: " << s.tellp() << std::endl;
        std::cout << "get pointer: " << s.tellg() << std::endl;
        std::cout << std::endl;
        s.seekp(2);
        std::cout << "put pointer: " << s.tellp() << std::endl;
        std::cout << "get pointer: " << s.tellg() << std::endl;
        std::cout << std::endl;
        s.seekg(4);
        std::cout << "put pointer: " << s.tellp() << std::endl;
        std::cout << "get pointer: " << s.tellg() << std::endl;
        std::cout << std::endl;
    }
    

    Output:

    put pointer: 0
    get pointer: 0
    
    put pointer: 2
    get pointer: 0
    
    put pointer: 2
    get pointer: 4
    

    Also the behaviour you describe sounds like it doesn't comply with the quotes here:

    Sets the position of the get pointer. The get pointer determines the next location to be read in the source associated to the stream.

    and here:

    Sets the position of the put pointer. The put pointer determines the location in the output sequence where the next output operation is going to take place.

提交回复
热议问题