简体   繁体   中英

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;
}

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.

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.

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