tags:

views:

287

answers:

1

Hello all.

I am currently attempting to read in Hex values from a text file.

There can be multiple lines of Hex's and each line can be as long as needed:

  f53d6d0568c7c7ce

  1307a7a1c84058

  b41af04b24f3eb83ce

Currently, I put together a simple loop to read in the Hex values into an unsigned char line[500] with fscanf as such:

  for(i=0; i < 500; i++)
  {
        if (fscanf(fp, "%02x", &line[i]) != 1) break;
  }

At the current moment, this only reads in the first line. As well, it is definitely not the best approach to just throw in a random 500 there to read.

I was assuming I could use sscanf with fgets or something of that nature. But I was unsure if this would be the best approach.

If anyone could help point me in the right direction, I would greatly appreciate it.

+3  A: 

You're on the right track with fgets() and sscanf(); that will let you size everything appropriately. If your data is really in that format, sscanf() might be overkill; you could just write a quick conversion loop yourself and save all those variadic function calls.

Carl Norum
Just remember `toupper()` and `tolower()` in the `ctype.h` header before we roll our own hex converter. Supporting case-insensitive hex data is never a bad thing.
Chris Lutz
@Chris, absolutely; good call.
Carl Norum