gpt4 book ai didi

C++以网络字节顺序读取文件

转载 作者:行者123 更新时间:2023-11-30 02:46:43 25 4
gpt4 key购买 nike

我正在尝试以网络字节顺序格式读取 C++ 中的文件。

到目前为止我尝试过(只是为了读取第一个整数(2 字节)):

ifstream in ("input.dat", ios::in|ios::binary);
unsigned short x;
in >> x;

以及我在网上找到的一些其他解决方案。似乎都没有用。

提前谢谢你,

最佳答案

in >> x 如果您将其作为二进制数据进行处理,则意义不大。 operator >> 用于格式化提取。您可能应该使用 std::istream::read()方法并在其后使用 ntohs()

像这样:

#include <cstdint>
#include <netinet/in.h>

ifstream in ("input.dat", ios::in|ios::binary);
uint16_t x;

if (in.read(reinterpret_cast<char*>(&x), sizeof(x)))
{
x = ntohs(x);

// use x here
}

...假设您的文件是原始二进制文件。还要注意类型的变化。对于任何平台独立性,被读取的条目最好是 16 位宽,作者也应该意识到这一点。

关于C++以网络字节顺序读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com