I am trying to write a stringstream
into a file but it not working.
int main() {
std::stringstream stream;
stream << "Hello world";
cout << stream.rdbuf()<<endl;//prints fine
std::ofstream p{ "hi.txt" };
p << stream.rdbuf();//nothing is writtten
p.close();
std::ifstream ip{ "hi.txt" };
std::string s;
ip >> s;
cout << s;//nothing printed
p.close();
return 0;
}
This answer here follows the same process. But it's not working in my case.
CodePudding user response:
Internally, the stringstream
maintain a read pointer/offset into its data buffer. When you read something from the stream, it reads from the current offset and then increments it.
So, cout << stream.rdbuf()
reads the entire stream's data, leaving the read pointer/offset at the end of the stream. Thus, there is nothing left for p << stream.rdbuf()
to read afterwards. In order to do that, you have to seek the read pointer/offset back to the beginning of the steam, eg:
cout << stream.rdbuf() << endl;
stream.clear(); // resets the error state, particularly eofbit
stream.seekg(0);
p << stream.rdbuf();
CodePudding user response:
The C file streams use input and output pointers to keep track of it's data buffer. When you write something it is written from the position where the current write pointer is or we can say the write pointer offset is added and then the data is simply written, after which the write pointer is incremented by that much value
The stream.rdbuf()
function reads all the data in the current file and leaves the read pointer at the end of the file so when we run the same function again there is nothing to read
This can Simply be solved by using stream.seekg(0)
cout << stream.rdbuf() << endl;
stream.seekg(0); //This puts the pointer at the beginning of the file
p << stream.rdbuf(); //Should work'