简体   繁体   English

如何将文件的内容读取到静态声明的变量中?

[英]How to read contents of a file to a statically declared variable?

I have a data file in binary where the first four bytes are some integer that I want to read.我有一个二进制数据文件,其中前四个字节是我想读取的一些 integer。 I simply do:我只是这样做:

int * num_rounters_p = malloc(sizeof(int));
fread(num_rounters_p, 4, 1, p_file);

printf("%d\n", *num_routers_p); // 10

This works fine (and please tell me if it doesn't,), however I do know the size of this particular value.这很好用(如果没有,请告诉我),但是我确实知道这个特定值的大小。 and so it isn't really necessary to store it dynamically.因此实际上没有必要动态存储它。

Is it possible to do something like是否可以做类似的事情

int x = some_read_function(4, 1, p_file);

printf("%d\n", x); // 10

Basically storing the value on stack instead of the heap?基本上将值存储在堆栈而不是堆上? The code example above is of course not grounded in C, but I hope I got my point across:))上面的代码示例当然不是基于 C,但我希望我明白我的意思:))

The most straightforward way would be最直接的方法是

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
}

An int is not guaranteed to be 4 bytes wide, it's only guaranteed to be at least 2 bytes wide, so it's safer to use sizeof num_routers than a literal 4 .不保证int为 4 字节宽,仅保证至少为2 字节宽,因此使用sizeof num_routers比使用文字4更安全。 Of course, that assumes that the binary file was written on the same platform that you're reading from.当然,这假设二进制文件是在您正在读取的同一平台上编写的。

Nvm.非易失性。 Easy fix: Just do:轻松修复:只需执行以下操作:

int num_routers;
fread(&num_routers, sizeof(int), 1, p_file);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM