Domanda

I have to copy first 64 bytes from input file in.wav into output file out.wav. (I've downloaded a program which shows .wav file's header (chunks): first 44 bytes and first 20 bytes of data_subchunk)

My code fills out.wav file with some values, but (I'm convinced) it to be a garbage. (The values that program shows don't match.)

I have to copy a part of in.wav file into out.wav:

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

typedef struct FMT
{
    char        Subchunk1ID[4];
    int         Subchunk1Size;
    short int   AudioFormat;
    short int   NumChannels;
    int         SampleRate;
    int         ByteRate;
    short int   BlockAlign;
    short int   BitsPerSample;

} fmt;

typedef struct DATA
{
    char        Subchunk2ID[4];
    int         Subchunk2Size;
    int         Data[441000]; // 10 secs of garbage. he-he)
} data;

struct HEADER
{
    char        ChunkId[4];
    int         ChunkSize;
    char        Format[4];
    fmt         S1;
    data        S2;
} header;


int main()
{
    FILE *input = fopen("in.wav", "r");
    FILE *output = fopen("out.wav", "w");

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

        fwrite(&input, sizeof(int), 16, output); // 16'ints' * 4 = 64 bytes

    fclose(input);
    fclose(output);

    return 0;
}

What is wrong?

È stato utile?

Soluzione

You are writing data to opened output file from input

fwrite(&input, sizeof(int), 16, output); 

I am not sure, if you can use FILE pointer this way. I would do that this way

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

Also open files in binary mode: fopen("in.wav", "rb") and fopen("out.wav", "wb")

Altri suggerimenti

You can't use a FILE pointer as input to fwrite. You actually have to read the data first into a buffer, before you write that buffer.

First, use binary mode for fopen ("wb" instead of "w"). Second, you are making an unsafe assumption, that is sizeof (int) == 4, which is not always true. Third, input is already a pointer, you don't need the & befor input on the fwrite line.

And, most importantly, you cannot use fwrite from one file handle to another. You need to copy to a char[] buffer before, like:

char buffer[40];
if (fread(buffer, sizeof (char), 40, input) != 40) {
    printf("Error!");
}
if (fwrite(buffer, sizeof (char), 40, output) != 40) {
    printf("Error!");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top