我想使用Cpp读取一个二进制文件,其类型是使用MsgPack 。 我不熟悉 MsgPack,我尝试先读取二进制文件并插入 MsgPack。这不起作用。它只是一次又一次地获取第一个数字。有人可以帮忙吗?非常感谢。
#include <bits/stdc++.h>
#include <msgpack.hpp>
using namespace std;
int main()
{
std::ifstream ifs("input.txt", std::ifstream::in);
std::stringstream buffer;
buffer << ifs.rdbuf();
msgpack::unpacked upd;
msgpack::unpack(upd, buffer.str().data(), buffer.str().size());
std::cout << upd.get() << std::endl;
return 0;
}
它只能获取第一个数字“3”。
我希望得到号码:
3
[3 6 7 5 3 5]
[6 2 9 1 2 7]
[0 9 3 6 0 6]
和here是输入的二进制文件。
最佳答案
msgpack::unpack()
解压第一个 MessagePack 格式的数据。
我认为 3
表示后面数组的数量。
在这种情况下,offset
很有用。请参阅https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_unpacker#client-controls-a-buffer
这里是读取第一个 MessagePack 数据 3
作为计数器的代码。然后调用 3 次 msgpack::unpack()
来解压每个数组。
在此过程中,变量 offset
会更新。
#include <iostream>
#include <fstream>
#include <msgpack.hpp>
int main()
{
std::ifstream ifs("input.txt");
std::string buffer((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
msgpack::unpacked upd;
std::size_t offset = 0;
msgpack::unpack(upd, buffer.data(), buffer.size(), offset);
std::size_t count = upd.get().as<std::size_t>();
std::cout << count << std::endl;
for (std::size_t i = 0; i != count; ++i) {
msgpack::unpack(upd, buffer.data(), buffer.size(), offset);
std::cout << upd.get() << std::endl;
}
}
我相信这是基于您的原始代码的方法。
关于c++ - 在 C++ 中使用 MsgPack 读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837630/