Search code examples
c++wavsha1

Parsing Data chuck of a .wav file in c++


I am using a SHA1 Hash to verify the authenticity of a .wav file. The SHA1 function I am using takes in three parameter:

  1. a pointer to the authentication file with .auth extension
  2. The data buffer read from the .wav file (which must be less than 42000 bytes in size)
  3. The length of the buffer
for (int i = 0; i < size_buffer; i++) {
    DataBuffer[i] = fgetc(WavResult);
}
util_sha1_calculate(&AuthContext, DataBuffer, size_buffer);

How can I set a read function to read 42000 bytes, transfer the data to util_sha1_calculate(&AuthContext, DataBuffer, size_buffer), and start from the position it left off when the loop is repeated, and proceed to read then next 42000 bytes?


Solution

  • You can put your shown for loop inside of another outer loop that runs until EOF is reached, eg:

    size_t size;
    int ch;
    
    while (!feof(WavResult))
    {
        size = 0;
        for (int i = 0; i < size_buffer; i++) {
            ch = fgetc(WavResult);
            if (ch == EOF) break;
            DataBuffer[size++] = (char) ch;
        }
        if (size > 0)
            util_sha1_calculate(&AuthContext, DataBuffer, size);
    }
    

    However, you should consider replacing the inner for loop with a single call to fread() instead, eg:

    size_t nRead;
    while ((nRead = fread(DataBuffer, 1, size_buffer, WavResult)) > 0)
    {
        util_sha1_calculate(&AuthContext, DataBuffer, nRead);
    }