使数据进入ostream以获取字节数组的最有效方法是什么?

时间:2014-01-09 03:43:09

标签: c++ stringstream ostream

我有一个需要调用的函数,它需要一个ostream。

我想要的是char数组中的数据,char *。

所以我要做的是将ostream数据复制到imageBytes中。问题是,这对我来说似乎效率低下,我只是想将数据放入char [ONE_MEGABYTES]。将它输出到字符串流似乎是一种非常间接的方式。我怎么能更有效率地做到这一点?

    #define ONE_MEGABYTE 1048576

    volatile char* imageBytes = new char[ONE_MEGABYTE];

    stringstream pngImageStringStream(ios_base::in | ios_base::out | ios_base::binary);
    image.write_stream(pngImageStringStream);
    imageLength = pngImageStringStream.tellp();
    memcpy( (void*)imageBytes, (void*)pngImageStringStream.str().c_str(), imageLength);

1 个答案:

答案 0 :(得分:1)

最有效的方法是使用read

pngImageStringStream.read(imageBytes, imageLength);