-1

我无法解决这个问题。我不知道为什么我会收到此错误消息。

在 Project2.exe 中的 0x7642DEB5 (KernelBase.dll) 处引发异常:0xC0000005:访问冲突写入位置 0x00000000。

错误在ReadFile(file,lpBuffer, nNumberOfBytesToRead-1, NULL, NULL)

这是我的代码。我正在尝试访问 JPG 文件以读取其标题。

#include<Windows.h>
#include<iostream>

int main()
{
    LPCTSTR path = "jpg.jpg";
    DWORD nNumberOfBytesToRead;

    HANDLE file = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (file == INVALID_HANDLE_VALUE)
    {
        std::cout << "The file couldnt be opened" << std::endl;
    }

    nNumberOfBytesToRead = GetFileSize(file, NULL);

    BYTE *lpBuffer = new BYTE[nNumberOfBytesToRead-1] ;

    if (ReadFile(file,lpBuffer, nNumberOfBytesToRead-1, NULL, NULL))
    {
        delete[] lpBuffer;
        CloseHandle(file);
        std::cout << "The file couldnt be read" << std::endl;
    }
    CloseHandle(file);
    delete[] lpBuffer;

    if (file != 0)
    {
        std::cout << "The file has been closed" << std::endl;
    }

    system("PAUSE");
    return 0;
}

谢谢我已经解决了这个问题。我还有一个问题

lpBuffer = 0xcccccccc 读取字符串字符时出错。>

在此处输入图像描述

这是我的新代码。

#include<Windows.h>
#include<iostream>

int main()
{
LPCTSTR path = "jpg.jpg";
DWORD nNumberOfBytesToRead = 0;
DWORD nNumberOfBytesRead = 0;
HANDLE file = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if (file == INVALID_HANDLE_VALUE)
{
    std::cout << "The file couldnt be opened" << std::endl;
}

nNumberOfBytesToRead = GetFileSize(file, NULL);

BYTE *lpBuffer = new BYTE[nNumberOfBytesToRead];

if (ReadFile(file, lpBuffer, nNumberOfBytesToRead, &nNumberOfBytesRead, NULL))
{
    std::cout << "The file couldnt be read" << std::endl;
}

CancelIo(file);
CloseHandle(file);
delete[] lpBuffer;

system("PAUSE");
return 0;
}
4

1 回答 1

2

错误消息告诉您访问冲突是由于写入内存地址 0x00000000 所致。

这是因为您将 NULL 指针传递lpNumberOfBytesReadReadFile().

根据ReadFile()文档

lpNumberOfBytesRead [输出,可选]

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

只有当 lpOverlapped 参数不为 NULL 时,该参数才能为 NULL。

您正在传递NULLlpOverlapped,因此您不能将 NULL 传递给lpNumberOfBytesRead。您必须将指针传递给已分配DWORD以接收实际读取的字节数,例如:

DWORD nNumberOfBytesRead;
...
if (ReadFile(file, lpBuffer, nNumberOfBytesToRead-1, &nNumberOfBytesRead, NULL))
于 2018-06-09T06:20:17.717 回答