[英]How to read contents of a file to a statically declared variable?
我有一个二进制数据文件,其中前四个字节是我想读取的一些 integer。 我只是这样做:
int * num_rounters_p = malloc(sizeof(int));
fread(num_rounters_p, 4, 1, p_file);
printf("%d\n", *num_routers_p); // 10
这很好用(如果没有,请告诉我),但是我确实知道这个特定值的大小。 因此实际上没有必要动态存储它。
是否可以做类似的事情
int x = some_read_function(4, 1, p_file);
printf("%d\n", x); // 10
基本上将值存储在堆栈而不是堆上? 上面的代码示例当然不是基于 C,但我希望我明白我的意思:))
最直接的方法是
int num_routers;
size_t items_read = fread( &num_routers, sizeof num_routers, 1, p_file );
if ( items_read < 1 )
{
// read error, handle as appropriate
}
else
{
// do something with num_routers
}
不保证int
为 4 字节宽,仅保证至少为2 字节宽,因此使用sizeof num_routers
比使用文字4
更安全。 当然,这假设二进制文件是在您正在读取的同一平台上编写的。
非易失性。 轻松修复:只需执行以下操作:
int num_routers;
fread(&num_routers, sizeof(int), 1, p_file);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.