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:

  1. Read a .wav file

    • Parse the header
    • Read the data
  2. Manipulate the data

  3. 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

2 answers

  • answered 2018-06-25 08:45 jspcal

    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 ('\0').

  • answered 2018-06-25 08:46 Shloim

    fread is not intended to read strings. It reads binary data. This means that the data will not be null terminated, nor have any other termination.

    fread returns 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.