Reputation: 11
So in this code what im trying to do is read the initial 44 bytes from a wave file put to a new file then calculate combination by using a sequence of left-right shorts
new file : (intial 44bytes - combination - combination - combination...) but it stops when I try to call fwrite.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE * firstFile;
FILE * finalFile;
size_t size;
char *buffer;
short left;
short right;
short combination;
int loop;
printf("%s", argv[1]);
if ((firstFile = fopen("test.wav", "rb")) == NULL) {
printf("File error");
exit(1);
}
fseek(firstFile, 0, SEEK_END);
size = ftell(firstFile);
fseek(firstFile, 0, SEEK_SET);
buffer = malloc(44);
fread(buffer, 1, 44, firstFile);
finalFile = fopen("new.wav", "rb");
fwrite(&buffer, sizeof(buffer), 1, finalFile);
loop = 1;
while (loop == 1) {
fread(&left, sizeof(short), 1, firstFile);
if (fread(&right, sizeof(short), 1, firstFile) == 0) {
loop = 0;
}
combination = (left - right) / 2;
fwrite(&combination, sizeof(short), 1, finalFile);
}
fclose(firstFile);
fclose(finalFile);
free(buffer);
return 0;
}
Upvotes: 1
Views: 332
Reputation:
You opened file in read mode. That's why this issue happened, per the man page of fopen. Please try write mode.
Upvotes: 1
Reputation:
Please open file in Write mode , Like "wb"
finalFile = fopen("new.wav", "wb");
then you have to check the return values
Upvotes: 2
Reputation: 1
You forgot to test the failure of fopen
like:
finalFile = fopen("new.wav", "wb");
if (!finalFile) { perror("new.wav"); exit(EXIT_FAILURE); }
And if you write a file, open it in write mode.
You should of course compile with all warnings & debug info:
gcc -Wall -Wextra -g yoursource.c -o yourbinary
and use the debugger (gdb
)
Upvotes: 3
Reputation: 461
You just opened write file in "rb" mode.
finalFile = fopen("new.wav", "rb");
Please try
finalFile = fopen("new.wav", "wb");
and check
finalFile==NULL
Upvotes: 3