Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Here is a modified version with error checking:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    unsigned int 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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading