简体   繁体   中英

I'm having trouble scanning hex values into an array in C

I am trying to scan a .dat file containing hex values into an array using fscanf(). My program successfully scans the file and puts values into the array, but when I print them back out to console, the values are drastically different. The following code is my function that opens the file and scans it. I'm using a test.txt file right now that has the values "1 2 3 4 5 6 7 8 9 abcdef" in it. When I run the program what prints in the console is 5 hex values that change after each run followed by "0 ffffffff 0 0 0".

void sim(int bytes, int lines, int sets, int policy){
    int i = 0;
    int total_Misses = 0;
    int total_References = 0;
    FILE *f1 = fopen("test.txt", "r");
    if (f1 == NULL){
        printf("File failed to open");
        exit(0);
    }
    unsigned int a[10];

    while (i < 10){

        fscanf(f1, "%x", &a[i]);
        printf("%x ", a[i]);
        i++;
    }
}

The code looks OK and all comments point to a problem with the input. I suggest you adapt the code to the following to catch errors:

while (i < 10){

    if (fscanf(f1, "%x", &a[i])==1) {
        printf("%x ", a[i]);
        i++;
    }
    else printf ("Error reading field %d\n", i);
}

Ps: a[10] is an automatic variable and not initialized. Hence not reading a value for the array entry will print the uninitialzed garbage value you are experiencing.

Pps: I often see scanf gurus add a space before the % sign to skip leading white space.

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