ReadFile C ++上的访问冲突异常[重复](Access Violation Exception on ReadFile C++ [duplicate])

这个问题在这里已有答案:

在LockFileEx 2应答 后调用ReadFile时崩溃

所以我试图通过使用ReadFile将文件读入文件缓冲区,但每次抛出此异常

我不明白为什么它有写入访问冲突,文件确实存在,我可以在Visual Studio autos watch中看到文件句柄,缓冲区和文件大小

int main() { LPCSTR Dll = "C:\\Test.dll"; HANDLE hFile = CreateFileA(Dll, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); // Open the DLL DWORD FileSize = GetFileSize(hFile, NULL); PVOID FileBuffer = VirtualAlloc(NULL, FileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // Read the file ReadFile(hFile, FileBuffer, FileSize, NULL, NULL); return 0; }

This question already has an answer here:

Crash when calling ReadFile after LockFileEx 2 answers

So i'm trying to Read a file into a file buffer by using ReadFile, but every time it throws this exception

I don't understand why it has an access violation for writing, the file does exist, and I can see the file handle, buffer and file size in the Visual Studio autos watch

int main() { LPCSTR Dll = "C:\\Test.dll"; HANDLE hFile = CreateFileA(Dll, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); // Open the DLL DWORD FileSize = GetFileSize(hFile, NULL); PVOID FileBuffer = VirtualAlloc(NULL, FileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // Read the file ReadFile(hFile, FileBuffer, FileSize, NULL, NULL); return 0; }

最满意答案

文档说明了最后两个参数:

lpNumberOfBytesRead [out,optional]

指向变量的指针,该变量接收使用同步hFile参数时读取的字节数。 在执行任何工作或错误检查之前,ReadFile将此值设置为零。 如果这是一个异步操作以避免可能的错误结果,请对此参数使用NULL。

仅当lpOverlapped参数不为NULL时,此参数才可以为NULL。

所以你应该用一个指向要写入的有效目标的指针来调用它,而不是NULL :

DWORD outSize = 0; ReadFile(hFile, FileBuffer, FileSize, &outSize, NULL);

The documentation says about the last two parameters:

lpNumberOfBytesRead [out, optional]

A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

This parameter can be NULL only when the lpOverlapped parameter is not NULL.

So you should call it with a pointer to a valid target to write to, instead of NULL:

DWORD outSize = 0; ReadFile(hFile, FileBuffer, FileSize, &outSize, NULL);

更多推荐