Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio std::stringstream pubsetbuf does not work

pubsetbuf member of std::stringbuf is not working at all in Visual Studio 2010!

The code:

char *FileData = ... ;
unsigned long long FileDataLen = ... ;
std::stringstream *SS = new std::stringstream(std::stringstream::in | std::stringstream::out);
SS->rdbuf()->pubsetbuf( FileData, (std::streamsize)FileDataLen );

pubsetbuf does nothing in Visual Studio!!!

Workaround #1:

std::stringstream *SS = new std::stringstream( std::string(FileData, (size_type)FileDataLen ) ),std::stringstream::in | std::stringstream::out);

Workaround #2:

SS->rdbuf()->sputn(FileData, (streamsize)FileDataLen);

But both of these workarounds produce unnecessary memory copying. I definitely need a working pubsetbuf member of std::stringbuf.

like image 494
Didar_Uranov Avatar asked Nov 29 '25 05:11

Didar_Uranov


2 Answers

putsetbuf only makes sense for fstream (technically, for std::basic_filebuf), where the buffer and the stream are two different things.

For stringstream (technically, std::basic_stringbuf) they are one and the same std::string.

If you need a stream that works on a string that's external to it, consider std::strstream: or boost::iostreams::array_sink

like image 56
Cubbi Avatar answered Dec 01 '25 19:12

Cubbi


basic_ios.clear() If you need to change rdbuf, call this first or it'll fail to work.

std::ifstream file("file1.txt"); // file1.txt contains "Welcome!"
std::stringstream ss;
ss << file.rdbuf();

std::cout << ss.str() << std::endl;

Outputs "Welcome!".
Let's try again with a new file.

// Empty it
file.close();
ss.str("");

// New file
file.open("file2.txt"); // file2.txt contains "Goodbye!"
ss << file.rdbuf();

std::cout << ss.str() << std::endl;

Outputs nothing.

ss.clear();
ss << file.rdbuf();
std::cout << ss.str() << std::endl;
file.close();

Outputs "Goodbye!"

like image 37
Sheer Ice Avatar answered Dec 01 '25 18:12

Sheer Ice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!