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
You're on the right track. Here's the problems I saw:
fopen() return NULL - you're printing an error message but then continuing.i >= 80, so you don't read more integers than you have space for.num[i], not the value, to fscanf.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
}