Read contents of a file as hex in C

前端 未结 4 426
孤独总比滥情好
孤独总比滥情好 2020-12-17 01:38

I have a file with hex values saved as hex.txt which has

9d ff d5 3c 06 7c 0a

Now I need to convert it to a character array as

4条回答
  •  没有蜡笔的小新
    2020-12-17 02:25

    Perform 2 passes through the file.
    1 Scan and count the required bytes.
    2 Allocate needed memory, then repeat scan, this time saving the results.

    size_t ReadHexFile(FILE *inf, unsigned char *dest) {
      size_t count = 0;
      int n;
      if (dest == NULL) {
        unsigned char OneByte;
        while ((n = fscanf(inf, "%hhx", &OneByte)) == 1 ) {
          count++;
        }
      }
      else {
        while ((n = fscanf(inf, "%hhx", dest)) == 1 ) {
          dest++;
        }
      }
      if (n != EOF) {
        ;  // handle syntax error
      }
      return count;
    }
    
    #include 
    int main() {
      FILE *inf = fopen("hex.txt", "rt");
      size_t n = ReadHexFile(inf, NULL);
      rewind(inf);
      unsigned char *hex = malloc(n);
      ReadHexFile(inf, hex);
      // do somehting with hex
      fclose(inf);
      free(hex);
      return 0;
     }
    

提交回复
热议问题