我无法解决这个问题。我不知道为什么我收到此错误消息。
在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读取字符串字符时出错。
enter image description here
这是我的新代码。
#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;
}
最佳答案
该错误消息告诉您访问冲突是由于写入内存地址0x00000000引起的。
这是因为您要将NULL指针传递给lpNumberOfBytesRead
的ReadFile()
参数。
根据ReadFile()
documentation:
lpNumberOfBytesRead [输出,可选]
指向变量的指针,该变量接收使用同步hFile
参数时读取的字节数。 ReadFile
在进行任何工作或错误检查之前将此值设置为零。如果这是异步操作,请对该参数使用NULL
以避免潜在的错误结果。
仅当lpOverlapped
参数不为NULL时,此参数才能为NULL。
您要将NULL
传递给lpOverlapped
,所以不能将NULL传递给lpNumberOfBytesRead
。您必须将指针传递给已分配的DWORD
,以接收实际读取的字节数,例如:
DWORD nNumberOfBytesRead;
...
if (ReadFile(file, lpBuffer, nNumberOfBytesToRead-1, &nNumberOfBytesRead, NULL))