从ReadFileEx使用CreateFile的有效句柄无效的句柄错误
问题描述:
我遇到的问题: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;
}
答
我的猜测是改变ReadFileEx(&file, &buffer, 1024, &overlapped, NULL);
到ReadFileEx(file, &buffer, 1024, &overlapped, NULL);
+0
谢谢。这显然是一个疏忽。它没有改变任何事情来解决这个问题,但我已经更新了这个问题来反映这个变化。我最初使用OpenFile写了这个,它给了我一个HFILE,而不是一个HANDLE。 (同样一个...... 0x194)当我改变命令时,我显然错过了标记的地址。 – GeekyGuy83
它抱怨未初始化overlapped.hEvent。 –