c++ - Is there a way to prepend a fixed number of bytes before a std:: stringbuf? -
i’m trying prepend 4 byte header existing std::stringbuf
object. example if data in stringbuf ‘h’,’e’,’l’,’l’,’o’
, header ‘0x00’,’0x10’, ‘0x00’,’0x0a’
need change stringbuf ‘0x00’,’0x10’, ‘0x00’,’0x0a’, ‘h’,’e’,’l’,’l’,’o’
. i’ve been trying below approach inefficent because has 3 copies of data in sbuf
, textstream
, buff. using new char[]
more problematic because needs continuous block of memory , can have large streams.
can me showing me how can in better optimized way? mean there way prepend bytes before existing stringbuf?
std::stringbuf createstreamwithheader(std::stringbuf &sbuf) { int = sbuf.str().size(); std::stringbuf textstreambuf; uint32_t streamsize = sbuf.str().size(); char* buff = new char [streamsize + 5]; //using char buffer not memory efficient needs big contonuous chunk of memory. zeromemory(buff, (streamsize + 5)*sizeof(char)); buff[0] = (streamsize >> 24) & 0xff; //in case header needs contain size of data in sbuf buff[1] = (streamsize >> 16) & 0xff; buff[2] = (streamsize >> 8) & 0xff; buff[3] = (streamsize >> 0) & 0xff; strcpy(&buff[4], sbuf.str().c_str()); //strcpy not right solution because fail if there’s null character in sbuf memcpy(&buff[4], sbuf.str().c_str(), streamsize); textstreambuf.sputn(buff, streamsize + 4); delete []buff; return textstreambuf; } int _tmain(int argc, _tchar* argv[]) { std::stringbuf stringbuffer, finalstringbuffer; stringbuffer.sputn("this string testing", 33); finalstringbuffer = createstreamwithheader(stringbuffer); return 0; }
you can, , should, without ever prepending:
- record streambuf position
- seek forward or write placeholder of correct size
- write other data.
- seek beginning.
- overwrite placeholder final value.
Comments
Post a Comment