fread in c reads more than instructed
I'm trying to write a program that will add effects to a .wav file.
The program should:
Read a .wav file
- Parse the header
- Read the data
Manipulate the data
- Create a new .wav file -
- Write the header
- Write the new data
I'm stuck on some weird thing with
fread() function -
when I'm trying to read 4 Bytes to the char array I've defined (of size 4 Bytes) - I'm getting the word + garbage.
If I try to read 2, or 3 Bytes in the same manner - everything works fine.
I tried printing the content of the array in both cases (when I read 2/3 Bytes v.s. when I read 4 Bytes) with a while loop until '\n' instead of printf("%s") - I got the same result (write string in the first case, string + garbage in the second case). Also, whem I write the header back and just COPY the data - the file that is created is NOT the same song! It does open - so the header is fine, but the data is garbage. I'll be very glad to hear some ideas for the possible reasons for this.. I'm really stuck on it, please help me guys! The problem - printscreen of the output
Perhaps reserve 5 bytes for your
fmt_chunk_marker. That will let you represent a 4-character string as a null-terminated C string. The byte after the last character read should be set to the null character (
freadis not intended to read strings. It reads binary data. This means that the data will not be null terminated, nor have any other termination.
freadreturns the amount of read bytes. After that point, the data will not be initialized, and must be ignored.
If you want to treat the data as string, you must null terminate it yourself with
arr[count]=0. Make sure that arr has a least count+1 capacity in order to avoid a buffer overflow.