are “seekp” & “seekg” interchangeable?

耗尽温柔 提交于 2019-11-29 02:59:17

For file positions they are the same. In other words there is only one pointer maintained.

From 27.9.1.1p3:

A joint file position is maintained for both the input sequence and the output sequence.

So, seekg and seekp are interchangeable for file streams. However, this is not true for other types of streams, as they may hold separate pointers for the put and get positions.

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 <sstream>
#include <iostream>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!