开发者

reading hex data from file fscanf format compile time warning

I'm reading some data from a file. The format is stated tobe

ASCII text with UNIX-style line-endings, a series of 32-bit signed integers in hexadecimal.

e.g

08000000

I'开发者_Go百科m using fscanf to read in this data.

long data_size;

FILE *fp;
fp=fopen("test01.bin", "r"); // open for reading
if (fp==0) {cerr << "Error openeing file"<<endl; return 1;}

fscanf(fp, "%x", &data_size);

Everything runs ok with my test file but I get the compile-time warning,

warning: format ‘%x’ expects type ‘unsigned int*’, but argument 3 has type ‘long int*’

however a hex value is unsigned and is being cast to a long dose this matter? As long will take the most significant bit as notifying the sign? Or will I end up with problems? Or am I well off the mark in my understanding?

Thanks


You should support the same pointer type as the warning states, or else you will run into serious troubles if you want to port your code to other architectures (e.g: 64 bit architectures) where long has a different size than int. This is especially tricky if you are using pointers. (I once had a bug originating from exactly this problem)

Just use int data_size and you will be fine.


The problem is that %x requires an unsigned int * to read the value in, but you have a long *. <stdint.h> header provides value types with fixed length, and <inttypes.h> defines corresponding macros for use with printf, scanf, and their derivatives. I think it'll be better for you to fscanf the data into an int32_t variable using the macro provided by <inttypes.h>:

#include <inttypes.h>

...

int32_t data_size;
fscanf(fp, "%" SCNx32, &data_size);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜