我无法解决这个问题。我不知道为什么会收到此错误消息。
Exception thrown at 0x7642DEB5 (KernelBase.dll) in Project2.exe: 0xC0000005: Access violation writing location 0x00000000.
错误于ReadFile(file,lpBuffer, nNumberOfBytesToRead-1, NULL, NULL)
这是我的代码。我正在尝试访问 JPG 文件以读取其 header 。
#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 Error reading characters of string.>
这是我的新代码。
#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 指针传递给 ReadFile()
的 lpNumberOfBytesRead
参数。
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. UseNULL
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.
您正在将 NULL
传递给 lpOverlapped
,因此您不能将 NULL 传递给 lpNumberOfBytesRead
。您必须将指针传递给分配的DWORD
以接收实际读取的字节数,例如:
DWORD nNumberOfBytesRead;
...
if (ReadFile(file, lpBuffer, nNumberOfBytesToRead-1, &nNumberOfBytesRead, NULL))
关于c++ - 我怎样才能解决我的win32读取图像文件代码中的这个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771440/