1

I am trying to read in hexadecimal from a text file, currently this is what I have

     void hexReader(char* file, node* head){
        FILE *fp;
        char str[MAXCHAR];

        size_t number = 0;

         fp = fopen(file, "r");
         if (fp == NULL){
         printf("Could not open file %s",filename);
        //return 1;
                                          }
           while (fgets(str, MAXCHAR, fp) != NULL) {
         //while ((number = getline(&line, &len, fp)) != -1)
             number = strtoull(str, NULL, 16);
             if (number > 0){
             printf("%size_t \n",number);
             printf("%x \n",number);

         }
       }
       fclose(fp);

  }

I have tried using unsigned long long for number but it fails on hex like FFFFFFFFFFFFFFF. I should be able to read in things like that, in the form of 0x....up to a 64 bit hex number.

Why is this failing? Size_t prints out nonesense and unsinged long long fails on too large of numbers.

Paul the Pirate
  • 697
  • 3
  • 7
  • 10

2 Answers2

1

Small re-write of inner loop.

1 No need for size_t.
2 Use errno to check for success of strtull().
3 Use correct unsigned long long specifier modifier "ll".
4 printf("%size_t \n",number) failed because the %s means to assume number is a string.
5 printf("%x \n",number) failed as sizeof(number) my be larger than sizeof(unsigned), which works with %x, was only using some of number.

while (fgets(str, MAXCHAR, fp) != NULL) {
  errno = 0;
  char *endptr;
  unsigned long long X = strtoull(str, &endptr, 16);
  // Use these tests as desired to catch overflow, no convert, unexpected extra.
  if (errno || (endptr == str) || (*endptr != '\n')) {
    printf("Error\n");
  }
  else {
    printf("%llx\n", X);  // print hex
    printf("%#llx\n", X);  // print hex with leading 0x
    printf("%#llu\n", X);  // print decimal
  }
}
chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213
1

%size_t is nonsense - use %zx to print a hexadecimal size_t value. Your %x won't work either - if you don't have the z modifier because you're using a non-C99-aware compiler/library, make sure you match variable type and format string:

printf("%llx\n", (unsigned long long)number);
Carl Norum
  • 201,810
  • 27
  • 390
  • 454