我有一些程序应该在调用程序后立即从命令行读取文件名。然后,它从文件中读取所有数据,包括标头数据等,这些数据定义为以下结构的一部分。

当我从另一个来源读取标头信息时,它告诉我我有29个节标头,但是当我使用自己的函数(如下)时,它说我有0。我不知道我是否在错误地打开此文件。这是怎么了?

这是我打开文件的方式:

int main(int argc, char *argv[])
{
    // open the file.
    FILE *fp = fopen(argv[1], "r");

    // read in the data.
    void *data = get_elf_data(fp);
}


这是标头结构:

typedef struct {
    unsigned char  identity[16];        // ELF specification information
    unsigned short nsectionheaders; // count of section headers in table
} FileHeader;


这是应该读取数据的函数:

static void *get_elf_data(FILE *fp)
{
    char ELF_IDENTITY[] = { 0x7f, 'E', 'L', 'F', ELFCLASS32, ELFDATA2LSB, EV_CURRENT};
    FileHeader hdr;
    int nread = fread(hdr.identity, 1, sizeof(ELF_IDENTITY), fp);  // read first bytes, verify proper ELF header
    if (nread < sizeof(ELF_IDENTITY) || memcmp(hdr.identity, ELF_IDENTITY, sizeof(ELF_IDENTITY)) != 0)
        return NULL; // reject if file doesn't have correct 32-bit Elf header

    fseek(fp, 0, SEEK_END);
    int size = ftell(fp);       // get number of bytes in entire file
    rewind(fp);
    void *data = malloc(size);
    if (!data)
        return NULL;
    nread = fread(data, 1, size, fp);  // read entire file into memory
    if (nread != size) return NULL;
    printf("The number of section headers %d\n", hdr.nsectionheaders);
    return data;

}


该函数也不返回NULL。

最佳答案

我认为,由于您不要求使用紧凑的结构,因此C编译器已使标头中的字段未对齐。

也许您最好逐个字符地读取它们,以独立于体系结构的方式构建标头字段。通常,如果您有一个四字节的整数并声明一个char,然后是一个short,则将short填充为16bit边界,从而在结构中留下一个洞(一个字节的洞)。

您可以使用C编译器来使字段在某些打包结构中正确对齐,但是执行此操作的详细信息取决于编译器。

在gcc中,可以通过以下方式完成:(从手册中借用)

      struct my_unpacked_struct
       {
          char c;
          int i;
       };

      struct __attribute__ ((__packed__)) my_packed_struct
        {
           char c;
           int  i;
           struct my_unpacked_struct s;
        };


但是您的编译器可以采用另一种方式。

注意:字段将以这种方式(在x86 intel上)对齐:


    偏移场
    ====== =====
    0 [my_packed_struct.c]
    1 [my_packed_struct.i.lsb]
    5 [my_packed_struct.s.c]
    9 [my_packed_struct.s.i.lsb]
    13 [完]



我不得不说这是一个复杂的示例,因为您将未对齐的未压缩结构放在了压缩结构的中间。

BR

关于c - 问题在C中打开和读取文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25136144/

10-11 22:11
查看更多