Read contents of a file as hex in C

前端 未结 4 427
孤独总比滥情好
孤独总比滥情好 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:14

    I can offer a code like this. Add proper includes.

    unsigned char * read_file(FILE * file) //Don't forget to free retval after use
    {
       int size = 0;
       unsigned int val;
       int startpos = ftell(file);
       while (fscanf(file, "%x ", &val) == 1)
       {
          ++size;
       }
       unsigned char * retval = (unsigned char *) malloc(size);
       fseek(file, startpos, SEEK_SET); //if the file was not on the beginning when we started
       int pos = 0;
       while (fscanf(file, "%x ", &val) == 1)
       {
          retval[pos++] = (unsigned char) val;
       }
       return retval;
    }
    

提交回复
热议问题