How do I read hex numbers into an unsigned int in C

前端 未结 5 942
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 04:59

I\'m wanting to read hex numbers from a text file into an unsigned integer so that I can execute Machine instructions. It\'s just a simulation type thing that looks inside

5条回答
  •  佛祖请我去吃肉
    2020-12-17 05:12

    You're on the right track. Here's the problems I saw:

    • You need to exit if fopen() return NULL - you're printing an error message but then continuing.
    • Your loop should terminate if i >= 80, so you don't read more integers than you have space for.
    • You need to pass the address of num[i], not the value, to fscanf.
    • You're calling fscanf() twice in the loop, which means you're throwing away half of your values without storing them.

    Here's what it looks like with those issues fixed:

    #include 
    
    int main() {
        FILE *f;
        unsigned int num[80];
        int i=0;
        int rv;
        int num_values;
    
        f=fopen("values.txt","r");
        if (f==NULL){
            printf("file doesnt exist?!\n");
            return 1;
        }
    
        while (i < 80) {
            rv = fscanf(f, "%x", &num[i]);
    
            if (rv != 1)
                break;
    
            i++;
        }
        fclose(f);
        num_values = i;
    
        if (i >= 80)
        {
            printf("Warning: Stopped reading input due to input too long.\n");
        }
        else if (rv != EOF)
        {
            printf("Warning: Stopped reading input due to bad value.\n");
        }
        else
        {
            printf("Reached end of input.\n");
        }
    
        printf("Successfully read %d values:\n", num_values);
        for (i = 0; i < num_values; i++)
        {
            printf("\t%x\n", num[i]);
        }
    
        return 0
    }
    

提交回复
热议问题