【问题标题】:How to use regular std::basic_istream::read, std::basic_ostream::write on a buffer of data in memory?如何在内存中的数据缓冲区上使用常规 std::basic_istream::read、std::basic_ostream::write?
【发布时间】:2020-12-02 06:32:45
【问题描述】:

我有一个QByteArray,想像使用普通文本文件一样使用它。如何在上面使用std::basic_istream::read之类的功能?

【问题讨论】:

  • 这个帖子可能有用:stackoverflow.com/questions/14086417/…
  • 听起来工作量很大。是否有特殊原因为什么您不使用它的 begin()(可能还有 end())迭代器来 std::copy()std::copy_n
  • @TedLyngmo,你的意思是我把它复制到另一个容器中?正如约翰帕克所说的那样?
  • 是的,有点。由于 Qt 的迭代器与 STL 兼容,因此您可以像使用任何 STL 迭代器一样使用它们。您也可以使用std::string from_byte_array(qt_byte_array.begin(), qt_byte_array.end()); 复制数据,或者如果您不想复制:std::string_view view_over_byte_array(qt_byte_array.begin(), qt_byte_array.size()); 也可以。由于您明确表示要将其用作文件,因此我没有对此做出回答。

标签: c++ qt file buffer


【解决方案1】:

QByteArray 数据类型接近于容器,而不是流。除非您继承内部处理 QByteArray 的 std::streambuf 类,否则您不能像处理文本文件一样处理它。

如果你不关心性能,你也可以考虑将 std::stringstream 转换为 QByteArray,

std::stringstream ss;
// write to ss ...
.
.
QByteArray qdata = QByteArray::fromStdString(ss.str());

对于读操作,

QByteArray qdata; // consider qdata is already filled with data.
std::stringstream ss(qdata.toStdString());

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 2016-07-10
    • 2017-09-29
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2019-03-05
    相关资源
    最近更新 更多