【问题标题】:Reading 2 byte at a time from a binary file从二进制文件一次读取 2 个字节
【发布时间】:2016-06-01 13:58:02
【问题描述】:

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

}

【问题讨论】:

  • strcat(pathInputFile, ".binary"); 覆盖尚未由您的程序分配的内存。
  • @user3646905 阅读一本好的 C 教科书或遵循教程。了解指针。
  • 为参数、扩展和终结符分配足够的内存,并检查fopen的结果。
  • 而你的 typedef typedef char* __string 是个坏主意。它让人相信存在“字符串”类型,但实际上 __string 只是指向 char 的指针。
  • 不要以两个下划线开头自己的标识符!以两个下划线开头的标识符(如__string)保留供标准库内部使用。

标签: c linux segmentation-fault ubuntu-14.04


【解决方案1】:

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

一种解决方案可能是:

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

【讨论】:

    【解决方案2】:

    将你的 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);
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 2012-07-11
    • 2020-11-20
    • 2020-09-06
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多