Reputation: 2806
im currently working on a c++ application which is using a c library which needs a callback implemented from my side for example the callback is defined as this:
int onWrite(char *what, char *buffer, size_t size, off_t offset);
i have std::set which needs to be formated and written into buffer and take care of size and offset where size is buffer's size and offset how many bytes have already been processed
is there a c++ way where i can stream-like into buffer? i think about something like this:
SomeSTLStandardStream stream(buffer,size);
stream.ignore(offset); // to drop the first n offset bytes
for(it=dataset.begin();it!=dataset.end() && stream.buffer_avail()>0;it++)
stream << *it << "|"; // format csv like for example
the core question i have is: is there a standard c++ way to grab just a slice of formated/streamed data and write into given buffer?
if not ill have to implement my own
i also had a look at stringstream but it doesnt seem to fit exactly to my needs cause its using its own write buffer instead of mine and i dont know how many bytes have already been written to it too and such....
thx
Upvotes: 4
Views: 17522
Reputation: 56549
You can allocate memory and wrap it in a string stream by using std::stringstream::pubsetbuf
:
int main()
{
char buf[1024];
std::stringstream stream;
stream.rdbuf()->pubsetbuf(buf, sizeof(buf));
stream<< "Hello " << "World " << std::endl;
std::string str;
std::getline(stream, str);
std::cout << str << std::endl;
//...
}
Read std::stringstream
, std::basic_streambuf
and std::basic_stringbuf
.
Upvotes: 4