Search code examples
cwavchunks

C, Wav File Chunk Sizes Issue


Given a WAV file, I'd like to print out the ChunkSize, SubChunk1Size and SubChunk2Size.

enter image description here

Below is the code I've written:

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

struct wavFile{

    char ChunkID[4]; //"RIFF", GOOD
    unsigned int ChunkSize;
    char Format[4]; //"WAVE", GOOD
    char Subchunk1ID[4]; //"fmt", GOOD
    unsigned int Subchunk1Size;  //GOOD
    unsigned short int AudioFormat; //GOOD
    unsigned short int NumChannels; //GOOD
    unsigned int SampleRate; //GOOD
    unsigned int ByteRate;
    unsigned int BlockAlign;
    unsigned int BitsPerSample;
    char SubChunk2ID[4]; //"data", prints weird symbols instead of "data"
    unsigned int Subchunk2Size;

};

int main()
{
    struct wavFile w;
    int headerSize = sizeof(w);
    FILE *fp;

    fp = fopen(wavFilePathGoesHere, "r");
    fread(&w, headerSize, 1, fp);



    printf("ChunkSize: %d, SubChunk1Size: %d, SubChunk2Size: %d\n", w.ChunkSize, w.Subchunk1Size, w.Subchunk2Size);
    //SubChunk2Size: -76154081

    fclose(fp);
    return 0;
}

The variables that I commented in the structure as "GOOD" actually give the correct values, so those are good. The printf statement gives a negative SubChunk2Size value (-76154081). Certainly, this can't be right. I don't know what I'm doing wrong here.


Solution

  • Use %u not %d for your printf of unsigned ints. See http://www.cplusplus.com/reference/cstdio/printf/ specifically

    specifier   Output                   Example
    d or i      Signed decimal integer   392
    u           Unsigned decimal integer 7235