ReadFileEx使用CreateFile的有效句柄时出现无效句柄错误

Invalid handle error from ReadFileEx using valid handle from CreateFile

本文关键字:句柄 无效 错误 ReadFileEx CreateFile 有效 使用      更新时间:2023-10-16

我遇到的问题:CreateFile返回0x194的句柄。ReadFileEx说这个句柄无效。(错误6)。什么好主意吗?传入的参数是"C:testfile.txt",这是我在记事本中创建的有效文本文件。尽管我做了12年的c++程序员,但这是我第一次用"windows.h"或线程写东西。

#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;
}

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

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