简体   繁体   中英

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.

//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. 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().

Please refer to : Man fgets() (for 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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