- 1 year ago
Why is ReadFileEx returning no data?
ReadFileEx
is an asynchronous read operation. When it is called, it initiates a read operation on the file handle specified by the hFile
parameter, and then immediately returns control to the calling thread. The actual read operation is performed asynchronously by the system.
If ReadFileEx
returns immediately with no data, it could be because the asynchronous read operation has not completed yet. In this case, you need to wait for the operation to complete by using an I/O completion routine or an I/O completion port.
Here is some example code that demonstrates how to use ReadFileEx
with an I/O completion routine:
c++#include <Windows.h>
#include <cstdio>
void CALLBACK ReadCompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
printf("ReadCompletionRoutine: %d bytes read\n", dwNumberOfBytesTransfered);
}
int main()
{
HANDLE hFile = CreateFile("test.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
printf("CreateFile failed with error %d\n", GetLastError());
return 1;
}
char buffer[1024];
OVERLAPPED overlapped = {};
overlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (overlapped.hEvent == nullptr) {
printf("CreateEvent failed with error %d\n", GetLastError());
return 1;
}
BOOL success = ReadFileEx(hFile, buffer, sizeof(buffer), &overlapped, ReadCompletionRoutine);
if (!success) {
printf("ReadFileEx failed with error %d\n", GetLastError());
return 1;
}
printf("Waiting for read operation to complete...\n");
WaitForSingleObject(overlapped.hEvent, INFINITE);
CloseHandle(overlapped.hEvent);
CloseHandle(hFile);
return 0;
}
In this example, we create a file handle to "test.txt" and an overlapped structure with an event handle. We then initiate an asynchronous read operation using ReadFileEx
. When the read operation completes, the system signals the event handle specified in the hEvent
member of the OVERLAPPED
structure. We wait for the event to be signaled using WaitForSingleObject
, and then we close the event handle and the file handle.
When you run this example, you should see the number of bytes read from the file printed to the console. If the ReadFileEx
call fails, you should see an error message printed instead.