如何打开文件并将信息复制到另一个文件。我只需要复制幻数和版本。void read_header(FILE * file,File * file2);
根据平台的不同,可能已经有定义此结构的头文件可用。例如,elf.h如果您正在运行linux,则可以尝试包括:
#include <elf.h>
#include <stdio.h>
void read_elf_header(const char* elfFile) {
// switch to Elf32_Ehdr for x86 architecture.
Elf64_Ehdr header;
FILE* file = fopen(elfFile, "rb");
if(file) {
// read the header
fread(&header, 1, sizeof(header), file);
// check so its really an elf file
if (memcmp(header.e_ident, ELFMAG, SELFMAG) == 0) {
// this is a valid elf file
}
// finally close the file
fclose(file);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的系统尚未包含,elf.h您可以在此处检查elf标头的结构。
然后,您可以创建一个结构来保存数据并像这样简单地读取它:
typedef struct {
uint8 e_ident[16]; /* Magic number and other info */
uint16 e_type; /* Object file type */
uint16 e_machine; /* Architecture */
uint32 e_version; /* Object file version */
uint64 e_entry; /* Entry point virtual address */
uint64 e_phoff; /* Program header table file offset */
uint64 e_shoff; /* Section header table file offset */
uint32 e_flags; /* Processor-specific flags */
uint16 e_ehsize; /* ELF header size in bytes */
uint16 e_phentsize; /* Program header table entry size */
uint16 e_phnum; /* Program header table entry count */
uint16 e_shentsize; /* Section header table entry size */
uint16 e_shnum; /* Section header table entry count */
uint16 e_shstrndx; /* Section header string table index */
} Elf64Hdr;
void read_elf_header(const char* elfFile, const char* outputFile) {
struct Elf64Hdr header;
FILE* file = fopen(elfFile, "rb");
if(file) {
// read the header
fread(&header, 1, sizeof(header), file);
// check so its really an elf file
if(header.e_type == 0x7f &&
header.e_ident[1] == 'E' &&
header.e_ident[2] == 'L' &&
header.e_ident[3] == 'F') {
// write the header to the output file
FILE* fout = fopen(outputFile, "wb");
if(fout) {
fwrite(&header, 1, sizeof(header), fout);
fclose(fout);
}
}
// finally close the file
fclose(file);
}
}
Run Code Online (Sandbox Code Playgroud)
使用打开你的 elf 文件fopen()
FILE *fp = fopen("youe_elf.bin","rb");
Run Code Online (Sandbox Code Playgroud)
现在使用fread()从文件读取数据块。并映射ELF 文件的格式并获取头字节并再次将它们写入新文件中fopen()
| 归档时间: |
|
| 查看次数: |
8451 次 |
| 最近记录: |