2011-10-07 120 views
0

我遇到的問題:CreateFile返回一個0x194的句柄。 ReadFileEx說這個句柄是無效的。 (錯誤6.)任何想法?傳入的參數是「C:\ testfile.txt」,這是我在記事本中創建的有效文本文件。儘管是過去12年來的C++程序員,但這是我第一次用「windows.h」或線程編寫任何東西。從ReadFileEx使用CreateFile的有效句柄無效的句柄錯誤

#include "stdafx.h" 
#include "stdio.h" 
#include "windows.h" 

using namespace System; 

int main(int argc, char **argv) 
{ 
    if (argc != 2) 
    { 
     printf("To display a file, you must enter the filename as the only command argument."); 
     scanf("\n"); 
     return 0; 
    } 
    HANDLE file; 
    int nameLen = (strlen(argv[1]) + 1); 
    wchar_t *filename = new wchar_t[nameLen]; 
    if (filename == 0) 
    { 
     printf("To display a file, you must enter the filename as the only command argument."); 
     scanf("\n"); 
     return 0; 
    } 
    memset(filename, 0, nameLen); 
    ::MultiByteToWideChar(CP_ACP, NULL, argv[1], -1, filename, nameLen); 
    file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
    if (file == NULL) 
    { 
     printf("A valid filename is required."); 
     scanf("\n"); 
     return 0; 
    } 
    char *buffer; 
    buffer = new char[1024]; 
    OVERLAPPED overlapped; 
    overlapped.Offset = overlapped.OffsetHigh = 0; 
    ReadFileEx(file, &buffer, 1024, &overlapped, NULL); 
    WaitForSingleObject(&file, 0); 
    if (GetLastError() != ERROR_SUCCESS) 
    { 
     printf("A valid file is required., Error: %d", GetLastError()); 
     scanf("\n"); 
     return 0; 
    } 
    printf("%s", buffer); 
    scanf("\n"); 
    delete buffer; 
    return 0; 
} 
+0

它抱怨未初始化overlapped.hEvent。 –

回答

1

我的猜測是改變
ReadFileEx(&file, &buffer, 1024, &overlapped, NULL);

ReadFileEx(file, &buffer, 1024, &overlapped, NULL);

+0

謝謝。這顯然是一個疏忽。它沒有改變任何事情來解決這個問題,但我已經更新了這個問題來反映這個變化。我最初使用OpenFile寫了這個,它給了我一個HFILE,而不是一個HANDLE。 (同樣一個...... 0x194)當我改變命令時,我顯然錯過了標記的地址。 – GeekyGuy83