Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file into struct

Tags:

c

struct

fread

I'm trying to read content of a file into a struct. The struct looks like this:

    typedef struct{
            unsigned char e_ident[EI_NIDENT] ;
            Elf32_Half e_type;
            Elf32_Half e_machine;
            Elf32_Word e_version;
            Elf32_Addr e_entry;
            Elf32_Off e_phoff;
            Elf32_Off e_shoff;
            Elf32_Word e_flags;
            Elf32_Half e_ehsize;
            Elf32_Half e_phentsize;
            Elf32_Half e_phnum;
            Elf32_Half e_shentsize;
            Elf32_Half e_shnum;
            Elf32_Half e_shstrndx;
    } Elf32_Ehdr;
extern Elf32_Ehdr elfH;

It's basically an ELF header file. So, anyways i want to load content of a file into this structure.

The function looks like this.

Elf32_Ehdr elfH;
int load(char* fname){
        FILE* file = fopen(fname,"r");

        if(NULL == file) return 0;

        fread(&elfH, 1, 52, file);

        fclose(file);
        return 1;
}

As it seems it's not working correctly. The content of elfH is not as expected. What might be the problem? Should i

like image 305
idjuradj Avatar asked Oct 31 '22 19:10

idjuradj


1 Answers

This is the code I've used to read the header from an ELF executable.

FILE* fp = fopen(fname, "rb");
if(fp == NULL)
{
    printf("failed to load\n");
    exit(1);
}

Elf32_Ehdr hdr;
if (1 != fread(&hdr, sizeof(hdr), 1, fp))
{
    printf("failed to read elf header\n");
    exit(1);
}
// If program doesn't exit, header was read and can be worked with down here.
like image 82
Isaac Drachman Avatar answered Nov 15 '22 04:11

Isaac Drachman