簡體   English   中英

從二進制文件一次讀取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);

}

您沒有空間將擴展連接到路徑,因此您必須為此創建空間。

一種解決方案可能是:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM