简体   繁体   English

如何在c中将一个二进制文件写入另一个文件

[英]how to write one binary file to another in c

I have a few binary files that I want to write into an output file. 我有一些二进制文件,我想写入输出文件。 So I wrote this function using a char as a buffer naively thinking it would work. 所以我用一个char作为缓冲器写了这个函数天真地认为它会起作用。

//Opened hOutput for writing, hInput for reading

void faddf(FILE* hOutput, FILE* hInput) {
    char c;
    int scan;
    do{
        scan = fscanf(hInput, "%c", &c);
        if (scan > 0)
          fprintf(hOutput, "%c", c);
    } while (scan > 0 && !feof(hInput));
}

Executing this function gives me an output of the few readable char 's in the beginning binary file. 执行此函数为我提供了开头二进制文件中几个可读char的输出。 So I tried it this way: 所以我这样试了:

void faddf(FILE* hOutput, FILE* hInput) {
  void * buffer;
  int scan;
  buffer = malloc(sizeof(short) * 209000000);
  fread(buffer, sizeof(short), 209000000, hInput);
  fwrite(buffer, sizeof(short), 209000000, hOutput);
  free(buffer);
}

This "works" but is only works when the file is smaller then my "magic number" Is there a better way? 这“工作”,但仅在文件小于我的“幻数”时才有效吗?有更好的方法吗?

You should avoid reading bytes per byte . 您应该避免每字节读取字节数 Use the fgets() function instead of fscanf(). 使用fgets()函数而不是fscanf().

Please refer to : Man fgets() (for Windows) 请参考: man fgets()(适用于Windows)

When you open both files next to each other (input one / output one), you're saying that the output file only contains readable characters... But can your text editor display unreadable characters on the input one ? 当您打开彼此相邻的两个文件(输入一个/输出一个)时,您说输出文件只包含可读字符......但是您的文本编辑器是否可以在输入文件上显示不可读的字符?

I should not have asked the question in the first place but here is how I ended up doing it: 我不应该首先问这个问题,但这是我最终如何做到的:

void faddf(FILE* hOutput, FILE* hInput) {
    void * buffer;
    int scan,size;
    size_t read;

    //get the input file size
    fseek(hInput, 0L, SEEK_END);
    size = ftell(hInput);
    fseek(hInput, 0L, SEEK_SET);

    //place the get space
    buffer = malloc(size);
    if (buffer == NULL)exit(1);//should fail silently instead

    //try to read everything to buffer
    read = fread(buffer, 1, size, hInput);

    //write what was read
    fwrite(buffer, 1, read, hOutput);

    //clean up
    free(buffer);
}

Although your new code (in the answer ) is much better than the old code, it can still be improved and simplified. 虽然您的新代码(在答案中 )比旧代码好得多,但它仍然可以改进和简化。

Specifically, you can avoid any memory problems by copying the file in chunks. 具体来说,您可以通过以块的形式复制文件来避免任何内存问题。

void faddf( FILE *fpout, FILE *fpin )
{
    char buffer[4096];
    size_t count;

    while ( (count = fread(buffer, 1, sizeof buffer, fpin)) > 0 )
        fwrite(buffer, 1, count, fpout);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM