【问题标题】:Stream processing errors with stream with embedded nulls带有嵌入空值的流的流处理错误
【发布时间】:2013-06-27 11:22:08
【问题描述】:

我有一个函数需要在与流一起使用的库中使用。实际的输入数据是嵌入空值的无符号字符缓冲区,实际上每个字节都可以是 0-255 之间的任何字符/整数。

我有库的源代码并且可以更改它。给定这样的字节流:

0x30, 0xb, 0x0, 0x6, 0x6

如果我使用从 char 缓冲区构造的 std::istringstream 流,只要在 read_stream 函数中达到 0x0,peek 就会返回 EOF???

当我尝试将流的内容复制到矢量流时,处理在到达空字符时停止。我怎样才能解决这个问题。我想将所有二进制字符复制到向量中。

#include <vector>
#include <iostream>
#include <sstream>

static void read_stream(std::istream& strm, std::vector<char>& buf)
{
   while(strm) {
      int c (strm.peek());
      if(c != EOF) {    // for the 3rd byte in stream c == 0xffffffff (-1) (if using istrngstream)
         strm.get();
         buf.push_back(c);
      }
   }
}


int main() {
   char bin[] = {0x30, 0xb, 0x0, 0x6, 0x6, 0x2b, 0xc, 0x89, 0x36, 0x84, 0x13, 0xa, 0x1};
   std::istringstream strm(bin);
   std::vector<char> buf;
   read_stream(strm, buf);

   //works fine doing it this way
   std::ofstream strout("out.bin",std::ofstream::binary);
   strout.write(bin, sizeof(bin));
   strout.close();
   std::ifstream strmf("out.bin",std::ifstream::binary);
   std::vector<char> buf2;
   read_stream(strmf, buf2);


   return 0;
}

编辑:

我现在意识到嵌入的 null 在流中没有特殊意义。所以这个问题一定和istringstream有关。

【问题讨论】:

  • 零字节在流中没有特殊意义。它们在 C 风格的字符串中用于终止字符串,但二进制流可以包含任何字节。包含多字节字符的文本文件也可能有零字节,因为它们是字符的一部分。

标签: c++ stream


【解决方案1】:

您将 C 风格的字符串(char 指针)传递给 std::istringstream constructor,它实际上会实例化 std::string 并传递它。这是由于隐式转换而发生的。 std::string 的转换构造函数将 C 样式字符串中的空字节字符解释为字符串结束符,导致其后面的所有字符都被忽略。

为避免这种情况,您可以显式构造一个std::string,指定数据的大小并将其传递给std::istringstream

char bin[] = {0x30, 0xb, 0x0, 0x6, 0x6, 0x2b, 0xc, 0x89, 0x36, 0x84, 0x13, 0xa, 0x1};
std::istringstream strm(std::string(bin, sizeof(bin) / sizeof(bin[0])));




注意:我不确切知道您要完成什么,但我建议尽可能使用std::vector 而不是原始字符缓冲区。

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 2021-06-25
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多