c++ streaming into char array?

陌路散爱 提交于 2020-01-25 10:28:47

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/16358669/c-streaming-into-char-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!