使用 stdio 加载数据时处理不同的架构

发布于 2024-11-19 11:29:23 字数 364 浏览 2 评论 0原文

我想从文件中读入一些数据。说一个整数:

fread(&var1, 4, 1, f);

其中 var1 是一个整数。但后来我开始认为这不安全,因为不能保证整数的长度是 4 个字节。 (为了这个问题,我忽略了其他问题,例如 feof 和ferror)。

我也很快意识到,除了 int 大小之外,还有更多问题,例如系统的字节顺序,以及可能还有其他我没有想到的问题。

那么,确保正确解释正在读入的数据的最佳方法是什么?到目前为止,我唯一能想到的就是将数据存储为文本而不是二进制数据,读取文本,并在运行时转换它。我猜想,无论解决方案如何,如果您想确保它是可移植的,它总是会涉及某种形式的转换。

谢谢。

I want to read in some data from a file. Say an integer:

fread(&var1, 4, 1, f);

Where var1 would be an integer. But then I got to thinking that this is not safe as there isn't any guarantee that an integer is 4 bytes long. (I'm ignoring other issues like feof and ferror for the sake of this question).

I also soon realised that there were even more issues than just int size, such as the endianness of the system, and probably others which I haven't even thought of.

So, what is the best way to ensure that you data being read in is interpreted properly? So far, the only thing I can think of is to just store the data as text rather than as binary data, read in the text, and convert it at run time. I would guess that no matter the solution though, if you wanted to ensure that it is portable, it would always involve some form of conversion anyway.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陪我终i 2024-11-26 11:29:23

为了避免大小问题,您应该这样做:

fread(&var1, sizeof(var1), 1, f);

如果您担心 int 的大小可能在写入数据的平台和读取数据的平台之间有所不同,那么您有更多根本问题。在这种情况下,应该避免使用 intshort 等,而使用 中定义的类型,例如如int16_tuint32_t

要处理字节顺序问题,您应该考虑编写辅助函数,以已知的顺序显式写入/读取各个字节,例如:

void write_uint32_t(uint8_t *buf, uint32_t x)
{
    buf[0] = (uint8_t)(x >> 0);
    buf[1] = (uint8_t)(x >> 8);
    buf[2] = (uint8_t)(x >> 16);
    buf[3] = (uint8_t)(x >> 24);
}

上述所有内容仅适用于整数类型。对于浮点类型,没有完美的通用解决方案。

To avoid the size problem, you should be doing:

fread(&var1, sizeof(var1), 1, f);

If you're worried that the size of int might vary between the platform that writes the data and the platform that reads the data, then you have a more fundamental problem. In this scenario, you should avoid using int, short, etc., and use the types defined in <stdint.h>, such as int16_t, uint32_t.

To deal with endianness issues, you should consider writing helper functions that explicitly write/read the individual bytes in a known order, such as:

void write_uint32_t(uint8_t *buf, uint32_t x)
{
    buf[0] = (uint8_t)(x >> 0);
    buf[1] = (uint8_t)(x >> 8);
    buf[2] = (uint8_t)(x >> 16);
    buf[3] = (uint8_t)(x >> 24);
}

All of the above applies only to integer types. For floating-point types, there is no perfect universal solution.

怎会甘心 2024-11-26 11:29:23

始终使用 sizeof() 运算符来获取类型的大小。永远不要依赖硬编码值!

Always use sizeof() operator for getting size of types. Never rely on hard coded values!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文