问题
Im trying to map the file to the memory and use MapViewOfFile(), but it failes with error code 6. I tried just about anything, I also read about big files being the problem, but the problem happens also with a 1kb file.
my code:
HANDLE hFile = CreateFile(pFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
e = GetLastError();
printf("CreateFile Errorcode %d\n", GetLastError());
if (hFile == INVALID_HANDLE_VALUE)
{
printf("Error: could not create handle to file");
printf("CreateFileMapping error code: %d", e)
return 1;
}
printf("successfully created a Handle to try.txt");
HANDLE pMap = CreateFileMapping(hFile, NULL, PAGE_EXECUTE_READWRITE,0 ,0 ,NULL);
e = GetLastError();
if (pMap == INVALID_HANDLE_VALUE)
{
printf("Error: Unable to CreateFileMapping\n");
printf("CreateFileMapping error code: %d", e)
return 1;
}
printf("CreateFileMapping successfull.")
LPVOID lpBase MapViewOfFile(pMap, FILE_MAP_ACCESS| FILE_MAP_EXECUTE, 0, 0, 0);
e = GetLastError();
if (!lpBase)
{
printf("Error: could not map file to memory");
printf("MapViewOfFile Errorcode %d\n", GetLastError());
CloseHandle(hFile);
UnmapViewOfFile(lpBase);
printf("closed hFile handle and unmapped lpBase.")
return 1;
}
the output is the following:
> successfully created a Handle to try.txt
> createFileMapping successfull
> Error: unable to MapViewOfFile
> MapViewOfFile errorcode: 6
> closed hFile handle and unmapped lpBase.
回答1:
Here:
HANDLE hFile = CreateFile(pFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
Replace GENERIC_READ
with GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE
Also there is no FILE_MAP_ACCESS
, but FILE_MAP_ALL_ACCESS
.
I tried this code and it maps test file with success, not sure what you want to do with it further. Also for inspecting problems you can also use: Procmon.exe from sysinternals - it will report you what problems occured during file manipulations.
来源:https://stackoverflow.com/questions/31813590/mapviewoffile-failes-with-errorcode-6-invalid-handle