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

时间:2016-06-01 13:58:02

标签: c linux segmentation-fault ubuntu-14.04

我有一个名为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);

}

2 个答案:

答案 0 :(得分:3)

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

一种解决方案可能是:

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指针不是一个好主意......

答案 1 :(得分:0)

将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);
    }
}
相关问题