I couldnt solve this problem. I dont know why im getting this error message.
Exception thrown at 0x7642DEB5 (KernelBase.dll) in Project2.exe: 0xC0000005: Access violation writing location 0x00000000.
Error at ReadFile(file,lpBuffer, nNumberOfBytesToRead-1, NULL, NULL)
Here my code. I am trying to access a JPG file to read its 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;
}
Thank you i have solved this problem. I have an another problem
lpBuffer = 0xcccccccc Error reading characters of string.>
Here my new code.
#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;
}
The error message is telling you that the Access Violation is due to memory address 0x00000000 being written to.
This is because you are passing a NULL pointer to the lpNumberOfBytesRead
parameter of ReadFile()
.
Per the ReadFile()
documentation:
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.
You are passing NULL
to lpOverlapped
, so you CANNOT pass NULL to lpNumberOfBytesRead
. You MUST pass a pointer to an allocated DWORD
to receive the number of bytes actually read, eg:
DWORD nNumberOfBytesRead;
...
if (ReadFile(file, lpBuffer, nNumberOfBytesToRead-1, &nNumberOfBytesRead, NULL))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments