简体   繁体   中英

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. 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:))

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 . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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