简体   繁体   中英

Read hex bytes from header file in C

I have a program that takes in command line arguments and a path to an elf file and displays the content of them using a struct . The elf header file is set up to have 16 bytes. Of those bytes, every two bytes describes something else about the header (version, entry point, etc) and the last four bytes hold a magic number that tells you it's the end of the file. The bytes are all in hex.

Header file:

bool read_header (FILE *file, elf_hdr_t *hdr)
{
  if(!file){
    return false;   
  }
  fseek(file,0,SEEK_END);
  long lsize=0,i=0;
  lsize = ftell(file);
  rewind(file);

  while(i<8){
    (*hdr).e_version = fgetc(file) +fgetc(file);
    i++;
  }
  fclose(file);
  return true;
}

Here is the struct that I am storing the values into.

typedef struct __attribute__((__packed__)) elf {
    uint16_t e_version;     /* version should be 1 */
    uint16_t e_entry;       /* entry point of program */
    uint16_t e_phdr_start;  /* start of program headers */
    uint16_t e_num_phdr;    /* number of program headers */
    uint16_t e_symtab;      /* start of symbol table */
    uint16_t e_strtab;      /* start of string table */
    uint32_t magic;         /* ELF */
} elf_hdr_t;

Obviously I didn't store all of the data, but I am lost on how I should go about storing the data at hand.

Assuming a matching endian, read the int16_t with fread() instead of fgetc() .

size_t cnt = fread(&((*hdr).e_version), sizeof ((*hdr).e_version), 1, file);
if (cnt != 1) Handle_Failure();

Depending on packing issues, file open mode, and endianness , code may be able to read the entire header with 1 fread() .

size_t cnt = fread(hdr, sizeof *hdr, 1, file);
if (cnt != 1) Handle_Failure();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM