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
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;
}