不能使用 fwrite 和写一个 int 来编辑二进制程序吗?

Cant edit a binary program using fwrite and writing an int?

我正在尝试编写一个程序,使用 fwritefseek 将数字写入两个不同的文件(二进制 elf 文件)偏移量,但两者似乎都正确地报告了写入和查找,但是 objdump -s 0x2db0 -n 0x16 test似乎没有变化。 fwritefseek 称为:

error = fwrite((void*)&value, sizeof(value), 1, file);
seek_error = fseek(file, offset, SEEK_SET);

整个程序像下面这样执行,应该在偏移量 0x2db00x01:

处写入 0x119e
./patch test 0x01 0x2db0 0x119e

所以当 运行 objdump 似乎根本没有发生任何变化时,而不是在两个偏移处看到 119e

整个源代码是:(主要检查函数 return 值)

#include <stdio.h>
#include <stdlib.h>
#include <zconf.h>
#include <errno.h>

int main(int argc, char *argv[]){
    long error, seek_error;
    long value, offset;

    if (argc < 5){
        fprintf(stderr, "Incorrect arg number\n");
        exit(1);
    }

    FILE* file = fopen(argv[1], "ab");
    if (file == NULL){
        fprintf(stderr, "Error openning File\n");
        perror("fopen() :");
        exit(1);
    }
    printf("\t\t File opened successfully\n");

    value = strtol(argv[4], NULL, 16); /* convert target value to int */
    if (value == LONG_MIN || value == LONG_MAX){
        fprintf(stderr, "Error calling strtol\n");
        perror("strtol() :");
        exit(1);
    }

    offset = strtol(argv[2], NULL, 16);
    printf("offset is %ld\n", offset);
    if (offset == LONG_MIN || offset == LONG_MAX) {
        fprintf(stderr, "Error calling strtol during offset\n");
        perror("strtol() :");
        exit(1);
    }

    seek_error = fseek(file, offset, SEEK_SET); /* From start go to end*/
    if (seek_error != 0){
        fprintf(stderr, "Error calling fseek\n");
        perror("fseek(): ");
        exit(1);
    }
    printf("File position is: 0x%lx\n", ftell(file));

    error = fwrite((void*)&value, sizeof(value), 1, file);
    if (error != 1){
        fprintf(stderr, "Error calling write\n");
        perror("write() :");
        exit(1);
    }
    printf("Number of bytes written %ld\n", error);

    offset = strtol(argv[3], NULL, 16);
    printf("offset is %ld\n", offset);
    if (offset == LONG_MIN || offset == LONG_MAX) {
        fprintf(stderr, "Error calling strtol during scond offset\n");
        perror("strtol() :");
        exit(1);
    }

    seek_error = fseek(file, offset, SEEK_SET);  /* Seek to the new offset */
    if (seek_error != 0){
        fprintf(stderr, "Error calling second fseek\n");
        perror("fseek(): ");
        exit(1);
    }
    printf("File position is: 0x%lx\n", ftell(file));

    error = fwrite((void*)&value, sizeof(value), 1, file);
    if (error != 1){
        fprintf(stderr, "Error calling write\n");
        perror("write() :");
        exit(1);
    }
    printf("Number of bytes written %ld\n", error);

    fflush(file);   /* flush changes not nesessecarly */
    error = fclose(file);
    if (error != 0){
        fprintf(stderr, "error closing file\n");
        perror("close() :");
        exit(1);
    }
}

您正在使用 fopen(argv[1], "ab") 以追加模式打开文件。所以所有的写入都在文件的末尾完成,忽略你想要的位置。

改用fopen(argv[1], "rb+")r表示以读模式打开,所以文件不先清空,+表示也允许写入。