2012-02-20 71 views
0

我以異步讀文件寫下面的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錯誤代碼說什麼?

謝謝!

+0

只需添加適當的初始化:'OVERLAPPED overlapped = {};'。 – avakar 2012-02-20 09:00:10

+1

此外,您可能要等待'INFINITE'時間,而不是0.另外,'NumberOfBytesRead'在等待後不會更新,您必須調用'GetOverlappedResult'來獲取它。 – avakar 2012-02-20 09:06:36

回答

3

也許你的問題是OVERLAPPED結構,你沒有正確初始化。 請參閱:「在結構用於函數調用之前,此結構中任何未使用的成員應始終初始化爲零,否則該函數可能會失敗並返回ERROR_INVALID_PARAMETER。」在這裏的評論:here。你可以使用memset清除它。

+1

確實,「無效句柄」可能是指'overlapped.hEvent'。 – 2012-02-20 08:11:57

+0

和..?我能做些什麼來解決它? – RRR 2012-02-20 08:30:39

+0

就像這樣:memset(&overlapped,0,sizeof(overlapped)),而不是你的overlapped.Offset = overlapped.OffsetHigh = 0;線。 – dbrank0 2012-02-20 08:49:56