一次从二进制文件中读取 2 个字节

Reading 2 byte at a time from a binary file

我有一个名为 example 的 elf 文件。我写了下面的代码,它以二进制模式读取示例文件的内容,然后我想将它们的内容保存在另一个名为 example.binary 的文件中。但是当我 运行 以下程序时,它显示了一个分段错误。这个程序有什么问题?我无法找出我的错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// typedef macro
typedef char* __string;

//Function prototypes
void readFileToMachine(__string arg_path);


int main(int argc, char *argv[]) {

    __string pathBinaryFile;

    if(argc != 2){
        printf("Usage : ./program file.\n");
        exit(1);
    }

    pathBinaryFile = argv[1];

    readFileToMachine(pathBinaryFile);

    return EXIT_SUCCESS;
}

void readFileToMachine(__string arg_path){

    int ch;
    __string pathInputFile = arg_path;
    __string pathOutputFile = strcat(pathInputFile, ".binary");

    FILE *inputFile = fopen(pathInputFile, "rb");
    FILE *outputFile = fopen(pathOutputFile, "wb");

    ch = getc(inputFile);

    while (ch != EOF){
        fprintf(outputFile, "%x" , ch);
        ch = getc(inputFile);
    }

    fclose(inputFile);
    fclose(outputFile);

}

您没有空间将扩展名连接到路径,因此您必须为此创建 space。

一个解决方案可能是:

char ext[] = ".binary";
pathOutputFile = strdup(arg_path);
if (pathOutputFile != NULL)
{
   pathOutputFile = realloc(pathOutputFile, strlen(arg_path) + sizeof(ext));
   if (pathOutputFile != NULL)
   {
       pathOutputFile = strcat(pathInputFile, ext);


      // YOUR STUFF
   }

   free(pathOutputFile);
}

旁注:typedef指针不是个好主意...

将您的 typedef 更改为 typedef char* __charptr

void rw_binaryfile(__charptr arg_path){

    FILE *inputFile;
    FILE *outputFile;

    __charptr extension = ".binary";
    __charptr pathOutputFile = strdup(arg_path);

    if (pathOutputFile != NULL){
        pathOutputFile = realloc(pathOutputFile, strlen(arg_path) + sizeof(extension));

        if (pathOutputFile != NULL){

            pathOutputFile = strcat(pathOutputFile, ".binary");

            inputFile = fopen(arg_path, "rb");
            outputFile = fopen(pathOutputFile, "wb");

            write_file(inputFile, outputFile);

            }
    }
}

void write_file(FILE *read, FILE *write){
    int ch;
    ch = getc(read);
    while (ch != EOF){
        fprintf(write, "%x" , ch);
        ch = getc(read);
    }
}