c - fscanf 没有正确读取文件 ~ 读取 HEX 格式字节的问题

标签 c file-io struct hex scanf

我目前正在尝试做一些我已经用 C++ 做过很多次的事情,但这是我第一次用 C 做。

我有一个包含 3 列的巨大文本文件:hexNumber unsignedChar int

adam  38      1
john  39      1
sara  3a      1
frank        3b      0
Christopher        3c      0
kate        3d      0

但是,就像我说的那样,文件很大,并且由于某种原因,它们之间的空白会有所不同。我不知道,我没有制作文件。按照我的理解,fscanf 由空格分隔,因此任何数量都可以,对吧?

我正在尝试将它读入一个结构数组,这是我的代码:

typedef struct node {
    unsigned char myHex;
    char* myString;
    int myInt;
} node;

void foo(bar* c){

    if( c == NULL )
        return;

    struct node nArr[205] ;

    //read in opcode information
    FILE *fp;
    fp = fopen( "input.txt" , "r" );

    if ( fp == NULL ) {
        fprintf( stderr, "Can't open input file file.txt!\n");
        exit(-1);
    }

    int it = 0;
    while( !feof( fp ) ){

        fscanf( fp , "%s%s%d\n" , nArr[it].myString ,
            &nArr[it].myHex , &nArr[it].myInt );
    }
...

但是,当我阅读它时,它充满了空白。打印出来显示:

myHex: 
myInt: 0
myString: (null)

最佳答案

要读取十六进制整数,应使用%x 格式说明符。另请注意 fscanf 的手册页关于 %x 说:“指针必须是指向 unsigned int 的指针。” 因此您应该更改:

while( !feof( fp ) ){

    fscanf( fp , "%s%s%d\n" , nArr[it].myString ,
        &nArr[it].myHex , &nArr[it].myInt );
}

到:

unsigned int hexVal = 0;
for( ; fscanf(fp , "%s %2x %d\n",
                   nArr[it].myString,
                   &hexVal,
                   &nArr[it].myInt) == 3 ; ++it) {
    nArr[it].myHex = hexVal;
}

并在您的结构中,更改:

char* myString;

char myString[MAX_LEN];

其中 MAX_LEN 是您输入中可能出现的最大长度。

关于c - fscanf 没有正确读取文件 ~ 读取 HEX 格式字节的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149161/

相关文章:

c - 使用双指针向结构输入值时出现问题

c++ - 无法获取存储在 vector 结构中的信息

c - 何时将 union 嵌套在结构中作为设计选择

c# - IOException 创建文件然后尝试访问它时

c - Qt 中对 NetWkstaUserGetInfo 的 undefined reference ,但在 VS 中有效

c - 文件处理 C 程序可以读取的格式

c - 文件是怎么写的?为什么我没有看到我的数据立即写入?

c - 如何在C中将结构转换为字节数组?

c - Embox 编译和烧写

c - 一小时后 PING 超时