0
votes

I'm trying to write PCM data (in a separate file) to the wav file I'm creating. I have already written the header and confirmed that worked but for some reason when I try to write the raw data into it, it doesn't. What I have successfully read the pcm file to a buffer and got the size of the file. The fwrite() process didn't give me an error either during compile however the resulting file is still empty. Any help is much appreciated! Thanks!

register FILE *handle;
register FILE *lever;
char filename[] = "test.wav";
handle = fopen(filename, "w");

lever = fopen("test.pcm","rb");
fseek(lever, 0, SEEK_END);
long int lSize = ftell(lever);
printf("%i \n",lSize);
rewind(lever);
char *buffer = (char*) malloc(sizeof(char)*lSize);
if (NULL == buffer) {printf("Error creating buffer \n");}
if (lSize != fread(buffer, 1, lSize, lever)) {
    printf("Reading error \n");
}

fwrite(buffer, sizeof(buffer), 1, handle);
free(buffer);

fclose(lever);
fclose(handle);
2
sizeof (buffer) == sizeof ( char*) - wildplasser
sizeof(char) == 1 by definition. - glglgl

2 Answers

2
votes

Change

fwrite(buffer, sizeof(buffer), 1, handle);

into:

fwrite(buffer, lSize, 1, handle);
1
votes

If you are running this under windows, it could fail because of text mode output file.

Use handle = fopen(filename, "wb");. Are you sure you have no errors while opening the files? Also your way of getting file size isn't optimal and it's better to use stat-family functions. And if malloc will fail you'll get a "Segmentation fault".

fwrite returns number of items written, or -1 on error. It sets errno so you can use perror or strerror.

EDIT: wildplasser's answer is the correct solution. Didn't notice this mistake.