输出流转换为String或std::ostream

Gio::OutputStream to a String or std::ostream

本文关键字:std ostream String 转换 输出流      更新时间:2023-10-16

我正在使用库libvtemm,它有一个函数write_contents。它接受一个内部缓冲区并将其输出到一个Glib::RefPtr<Gio::OutputStream>对象。我一直在试图找到一种方法将Gio::OutputStream的内容转换为std::string或类似的东西,以便我可以玩和移动内部的数据到其他数据结构。

有没有人知道如何将Gio::OutputStream构建为std::ostream或将其内容转换为std::string ?

我看到有一个Gio::MemoryOutputStream,这样的东西在抓取数据到std::ostream是有用的吗?

对于那些正在寻找答案的人,这里是我提出的将控制台缓冲区读取为std::string的方法。

// Create a mock stream just for this example
Glib::RefPtr<Gio::MemoryOutputStream> bufStream =
  Gio::MemoryOutputStream::create(NULL, 0, &realloc, &free);
// Create the stringstream to use as an ostream
std::stringstream ss;
// Get the stream size so we know how much to allocate
gsize streamSize = bufStream->get_data_size();
char *charBuf = new char[streamSize+1];
// Copy over the data from the buffer to the charBuf
memcpy(charBuf, bufStream->get_data(), streamSize);
// Add the null terminator to the "string"
charBuf[streamSize] = '';
// Create a string from it
ss << charBuf;

希望这对将来遇到类似问题的人有所帮助。