Search code examples
c++iofreadstdio

Reading a wav file returns 0 bytes


So I'm reading from .wav file but it returns 0 bytes.

    FILE *pFile = fopen("file.wav", "r");
    if (pFile == nullptr)
    {
        cout << "Unable to open wave file";
        return 1;
    }

    long lSize = ftell (pFile);
    char *p = new char[lSize];
    size_t bytesRead = fread(p, 1, lSize, pFile); // 0 bytes ```

Solution

  • You need to seek to the end before getting the file position, then rewind:

    FILE *pFile = fopen("file.wav", "rb");
    if (pFile == nullptr)
    {
        cout << "Unable to open wave file";
        return 1;
    }
    
    fseek(pFile, 0, SEEK_END); // <----- ADD THIS -------<
    
    long lSize = ftell (pFile);
    
    rewind(pFile); // <----- AND THIS -------<
    
    char *p = new char[lSize];
    size_t bytesRead = fread(p, 1, lSize, pFile);
    

    Make sure you open as read-binary. "rb" -- look at fopen method.