thebesttony
thebesttony

Reputation: 327

Copy a file in C

I try to copy a file in a new file but it doesn't work because the input is 5133KB and the output is 614byte... what's wrong? Thank you in advance.

#include <stdio.h>

int main(void)
{

    FILE * input    =   fopen("input.wav", "r");
    FILE * output   =   fopen("output.wav", "w");

    char    buffer;
    int     bytesRead = 1;

    while(bytesRead=fread(&buffer,1,1,input))
    {
        fwrite(&buffer,1,1,output);
    }

    fclose(input);
    fclose(output);

    return 0;
}

Upvotes: 2

Views: 105

Answers (1)

jxh
jxh

Reputation: 70382

You may need to open the file in binary mode on your system. From C.2011, §7.21.5.3:

rb open binary file for reading
wb truncate to zero length or create binary file for writing

So:

FILE * input    =   fopen("input.wav", "rb");
FILE * output   =   fopen("output.wav", "wb");

The reason is that on some systems, certain embedded binary characters may cause the text mode processing to believe the end of file has been encountered, even though there are actually more bytes in the file.

Upvotes: 4

Related Questions