【问题标题】:basic_streambuf<char> to uint8_t*basic_streambuf<char> 到 uint8_t*
【发布时间】:2021-03-30 19:16:19
【问题描述】:

我们有一个文件存在于数据存储 (S3) 中,其中包含 byte[] 形式的数据(使用 Java 语言上传)。

现在当我下载文件时,我得到的数据是 std::basic_streambuf 的形式(理想情况下它也应该有字节)。现在我想将此数据发送到另一个以 uint8_t* 作为输入的 API。

这样做的方法是什么?这样做有意义吗?

我试过了:


// Assume streambuf is:
std::streambuf *buf;

std::stringstream ss;
ss << buf;

// Solution1
const std::string output1 = ss.str(); 
cout<<output1;
// This prints the whole data with some weird characters (i think weird characters are valid because data is in byte form). Upon converting output1 to uint8_t*, the final data contains only 20 characters/bytes.

// Solution2
uint8_t* finalString;
ss >> finalString;
cout<<finalString;
// This prints only initial 20 characters/bytes and the remaining part is skipped.

因此,使用解决方案 1 和解决方案 2 都无法实现获得 uint8_t* 完整数据的最终目标。建议的方法是什么?

【问题讨论】:

  • Upon converting output1 to uint8_t* -> 是什么意思?您如何执行上述转换?
  • 是文本文件还是二进制文件?如果是文本,它有什么编码?

标签: c++ c++11 c++14


【解决方案1】:

您必须从缓冲区中读取数据(因为缓冲区本身可以在数据可用时将数据流式传输)。一种可能的实现是这样的:

vector<uint8_t> bytes;

do {
    bytes.push_back(buf->sgetc());
} while(buf->snextc() != EOF);

// your data is in bytes.data() of type uint8_t*

当然,如果您从一开始就知道字节数,而不必读取缓冲区即可找到,只需事先预先分配向量即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多