简体   繁体   English

从文件 fscanf 格式读取十六进制数据编译时警告

[英]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.带有 UNIX 风格行尾的 ASCII 文本,一系列 32 位十六进制有符号整数。

eg例如

08000000

I'm using fscanf to read in this data.我正在使用 fscanf 来读取这些数据。

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 (eg: 64 bit architectures) where long has a different size than int .您应该支持与警告状态相同的指针类型,否则如果要将代码移植到longint大小不同的其他架构(例如:64 位架构),您将遇到严重的麻烦。 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.只需使用int data_size就可以了。

The problem is that %x requires an unsigned int * to read the value in, but you have a long * .问题是%x需要一个unsigned int *来读取值,但是你有一个long * <stdint.h> header provides value types with fixed length, and <inttypes.h> defines corresponding macros for use with printf , scanf , and their derivatives. <stdint.h> header 提供了具有固定长度的值类型, <inttypes.h>定义了相应的宏以用于printfscanf及其派生类。 I think it'll be better for you to fscanf the data into an int32_t variable using the macro provided by <inttypes.h> :我认为您最好使用<inttypes.h>提供的宏将数据fscanfint32_t变量中:

#include <inttypes.h>

...

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

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

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