Is there anyway I can transfer data from an fstream
(a file) to a stringstream
(a stream in the memory)?
Currently, I'm using a buffer, but this requires double the memory, because you need to copy the data to a buffer, then copy the buffer to the stringstream, and until you delete the buffer, the data is duplicated in the memory.
std::fstream fWrite(fName,std::ios::binary | std::ios::in | std::ios::out);
fWrite.seekg(0,std::ios::end); //Seek to the end
int fLen = fWrite.tellg(); //Get length of file
fWrite.seekg(0,std::ios::beg); //Seek back to beginning
char* fileBuffer = new char[fLen];
fWrite.read(fileBuffer,fLen);
Write(fileBuffer,fLen); //This writes the buffer to the stringstream
delete fileBuffer;`
Does anyone know how I can write a whole file to a stringstream without using an inbetween buffer?
In the documentation for
ostream
, there are several overloads foroperator<<
. One of them takes astreambuf*
and reads all of the streambuffer's contents.Here is a sample use (compiled and tested):
The only way using the C++ standard library is to use a
ostrstream
instead ofstringstream
.You can construct a
ostrstream
object with your own char buffer, and it will take ownership of the buffer then (so no more copying is needed).Note however, that the
strstream
header is deprecated (though its still part of C++03, and most likely, it will always be available on most standard library implementations), and you will get into big troubles if you forget to null-terminate the data supplied to the ostrstream.This also applies to the stream operators, e.g:ostrstreamobject << some_data << std::ends;
(std::ends
nullterminates the data).