使用 stdio 加载数据时处理不同的架构
我想从文件中读入一些数据。说一个整数:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了避免大小问题,您应该这样做:
如果您担心
int
的大小可能在写入数据的平台和读取数据的平台之间有所不同,那么您有更多根本问题。在这种情况下,应该避免使用int
、short
等,而使用
中定义的类型,例如如int16_t
、uint32_t
。要处理字节顺序问题,您应该考虑编写辅助函数,以已知的顺序显式写入/读取各个字节,例如:
上述所有内容仅适用于整数类型。对于浮点类型,没有完美的通用解决方案。
To avoid the size problem, you should be doing:
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 usingint
,short
, etc., and use the types defined in<stdint.h>
, such asint16_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:
All of the above applies only to integer types. For floating-point types, there is no perfect universal solution.
始终使用 sizeof() 运算符来获取类型的大小。永远不要依赖硬编码值!
Always use
sizeof()
operator for getting size of types. Never rely on hard coded values!