yulian
yulian

Reputation: 1627

fread() doesn't work but fwrite() works?

Why fread() doesn't work but fwrite() works?

If I get fwrite() into comments and fread() out of comments, the output file is of 0 bytes size... But if fwrite() is out of comments, the output file is of 64 bytes size..

What is the matter?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *input = fopen( "01.wav", "rb");

        if(input == NULL)
        {
            printf("Unable to open wave file (input)\n");
            exit(EXIT_FAILURE);
        }

    FILE *output = fopen( "01_out.wav", "wb");


    //fread(output, sizeof(char), 64, input);
    fwrite(input, sizeof(char), 64, output);

    fclose(input);
    fclose(output);

    return 0;
}

Upvotes: 2

Views: 1309

Answers (2)

sepp2k
sepp2k

Reputation: 370455

fread(output, sizeof(char), 64, input);

This line will read 64 bytes from the input file and store those 64 bytes at the memory that output points to. It will not write anything to the output file. Since output is a file pointer and not a pointer to an array, it does not make sense to use it like this.

fwrite(input, sizeof(char), 64, output);

This line will read 64 bytes from the memory that input points to and write them to the output file. It will not read anything from the input file. Again this won't do what you want since the memory that input points to simply contains a FILE object and not the contents of the input file.

Upvotes: 1

jxh
jxh

Reputation: 70502

You should read from your input file, and write to your output file.

char buf[64];
fread(buf, 1, sizeof(buf), input);
fwrite(buf, 1, sizeof(buf), output);

Your code should check the return values of fread and fwrite for errors.

Upvotes: 3

Related Questions