About using seekp() & seekg() in the same streambuf, I thinks they shared the same of position indicator, but not sure

e.g.
#include
#include

int main(){
std::ifstream in2(“text.txt”, std::ios::in | std::ios::out);
std::ostream out2(in2.rdbuf()); //shared streambuf
std::cout << in2.rdbuf(); // set the input position indicator to ios::end
out2 << “aaaaaaaaaaaaaaaaa”; // the text inserted in end
out2.seekp(0, std::ios::beg); // set the output position indicator to ios::beg
out2 << “BBBBBBBBBBBBBBBBB”; // replace the text in beg
in2.seekg(0, std::ios::beg); std::cout << in2.rdbuf(); //Using seekg the input positon set to ios::beg
//otherwise the input postion is after “BBBBBBBBBBBBBB”

}

std::basic_ostream<CharT,Traits>::seekp

Overload 2: basic_ostream & seekp( off_type off, std::ios_base::seekdir dir );

sets the output position indicator to offset off relative to dir by calling rdbuf()->pubseekoff(off, dir, std::ios_base::out).

std::basic_istream<CharT,Traits>::seekg

Overload 2: basic_istream & seekg( off_type off, std::ios_base::seekdir dir);

sets the input position indicator to position off, relative to position, defined by dir. Specifically, executes rdbuf()->pubseekoff(off, dir, std::ios_base::in).

cppreference is your friend. (Also available in Chinese: seekp, seekg.)

Thanks Pharap!!!

1 Like