Billson
Billson

Reputation: 5

ReadFile returning INVALID_HANDLE on second call

I am trying to read data all of the data in a PCAPNG file in chunks only using the Windows API's.

I have the first read of the file working with ReadFile and the data that is being returned is correct but on our subsequent call, we are failing the ReadFile with INVALID_HANDLE.

    HANDLE hFile;
    DWORD dwBytesToRead = 32;
    DWORD dwBytesRead = 0;
    DWORD ReadBuffer[2] = {0};

    hFile = CreateFile(LogPath.c_str(), 
            GENERIC_READ,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);
    if(hFile == INVALID_HANDLE_VALUE)
        return false;

    while(ReadFile(hFile, ReadBuffer, dwBytesToRead, &dwBytesRead, NULL) && dwBytesRead > 0)
    {
         std::cout << "Data from ReadBuffer[0]: " << ReadBuffer[0] << std::endl;
         std::cout << "Data from ReadBuffer[1]: " << ReadBuffer[1] << std::endl;
    }

    std::cout << "Failed with: " << GetLastError() << std::endl;
    CloseHandle(hFile);

During the first iteration of the ReadFile, we are able to successfully read the content of the file but on the second iteration of the loop we run into an error of INVALID_HANDLE.

Basing this ReadFile loop on this documentation: https://learn.microsoft.com/en-us/windows/win32/fileio/appending-one-file-to-another-file

I am not sure what our failure reason is.

I've done some testing with SetFilePointer and the OVERLAPPED structure but I haven't had much success with either.

Am I misunderstanding the ReadFile API or is this not the right way to do what I am looking for?

Upvotes: 0

Views: 840

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

You're reading 32 bytes into a buffer that is only 8 bytes long.

You need to either change ReadBuffer to be larger, change the type from a DWORD to something that is 16 bytes long, or change dwBytesToRead to be the appropriate size (sizeof(ReadBuffer), and change the declaration order).

Upvotes: 3

Related Questions