Search code examples
cbinaryfiles

Reading in binary file and outputting to another binary file


So im trying to read a binary file into an array and then output that array into another file, which should therefor get me 2 identical files.

But they are different files files compared

Why would this be?

#include <stdio.h>

int main()
{
    unsigned int buffer[1000000];

    FILE *in;
    in = fopen("file.bin", "rb");  
    fread(buffer, sizeof(buffer), 1, in);
    fclose(in);

    FILE *out;
    out = fopen("out.bin", "wb");  
    fwrite(buffer, sizeof(buffer), 1, out);
    fclose(out);
    
    return 0;
}

This is the code I have tried


Solution

  • To copy the file, you must only write the bytes that have been read. For this purpose, you should make these modifications:

    • make buffer an array of char or unsigned char
    • pass the fread and fwrite 2nd and 3rd arguments in the opposite order: the 2nd argument is the array element size and the 3rd is the number of elements to read / write
    • store the return value of fread in a variable, this is the number of elements read, and pass that to fwrite.
    • repeat the process as long as elements can be read.

    Here is a modified version with error checking:

    #include <errno.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        unsigned char buffer[1000000];
        size_t len;
        int res = 0;
    
        FILE *in = fopen("file.bin", "rb"); 
        if (in == NULL) {
            perror("cannot open file.bin");
            return 1;
        } 
        FILE *out = fopen("out.bin", "wb");  
        if (out == NULL) {
            perror("cannot open out.bin");
            return 1;
        } 
        while ((len = fread(buffer, 1, sizeof(buffer), in)) != 0) {
            if (fwrite(buffer, 1, len, out) != len) {
                perror("cannot write out.bin");
                res = 1;
                break;
            }
        }
        fclose(in);
        fclose(out);
        return 0;
    }