Search code examples
cfilehexfgetsscanf

Read a hex file in C


I am attempting to read hex values from a text file.

There can be 20000 lines each of varying length.

0F61048C

1F1ED7F855A106CB20D574C24833

52D3C74F4101FC1143C6DE298933

CF8630C79991046C587474E4B858

6EF8745D6000ACDB3757ECEB79EB

I cannot use fgets because it converts each value to ASCII while storing in memory. I am thinking of using fscanf as there is format specifier %x. But how can i read an entire line using fscanf? I know this is not a best approach to read a line. Perhaps it is fgets, but fgets converts to ASCII, i do not want to use this. In fgets if there is hex line like, 01 04 05 FF, it stores in memory as 3031 3034 3035 4646. It is really cumbersome to convert this format back to 01 04 05 FF.

Can anybody help me with this? I am stuck with this problem for nearly 2 weeks.


Solution

  • You can certainly do this using fgets(), and it's probably much easier than using fscanf() for variable length lines. For example:

    char buf[200];
    while (fgets(buf, sizeof(buf), infile) != NULL) {
        unsigned char a[200];
        int i = 0;
        while (buf[i] != '\n') {
            int b; // must use int with sscanf()
            sscanf(&buf[i], "%2x", &b);
            a[i] = b;
            i += 2;
        }
    }
    

    The above has no error checking (non-hex digits, odd number of digits on line, etc). But it's the general idea.