我以異步讀文件寫下面的C++代碼:異步調用ReadFile函數返回6錯誤代碼
#define BUF_SIZE 1024
HANDLE hFile;
DWORD NumberOfBytesRead = 0;
BYTE *buf = (BYTE*)malloc(BUF_SIZE*sizeof(BYTE));
OVERLAPPED overlapped;
overlapped.Offset = overlapped.OffsetHigh = 0;
hFile = CreateFile("C:\\Users\\Desktop\\FOO.cpp",
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
printf("invalid hfile\n");
int i;
i= ReadFile(hFile,
&buf,
BUF_SIZE,
&NumberOfBytesRead,
&overlapped);
if(!i && GetLastError() != ERROR_IO_PENDING)
printf ("ReadFile failed with error %d.\n", GetLastError());
else
{
WaitForSingleObject(&(overlapped.hEvent), 0);
printf("here it is %d",NumberOfBytesRead);
}
CloseHandle(hFile);
但是從ReadFile的返回值是0,而最後一個錯誤等於6。 有沒有人有任何想法爲什麼?和6錯誤代碼說什麼?
謝謝!
只需添加適當的初始化:'OVERLAPPED overlapped = {};'。 – avakar 2012-02-20 09:00:10
此外,您可能要等待'INFINITE'時間,而不是0.另外,'NumberOfBytesRead'在等待後不會更新,您必須調用'GetOverlappedResult'來獲取它。 – avakar 2012-02-20 09:06:36