C CreateFileMapping error 5 Access Denied ALWAYS
winapi
Solution
You need to create the file with `GENERIC_WRITE | GENERIC_READ` to match `PAGE_READWRITE`.
That seems self-evident when you think about it. How can you have memory that you can read from backed by a file that you cannot read from? The documentation does call this out explicitly in any case:
PAGE_READWRITE
The file handle that the hFile parameter specifies must be created with the GENERIC_READ and GENERIC_WRITE access rights.
On top of that your error checking on the call to `CreateFile` is wrong. Take another look at the documentations. Error is indicated by a return value of `INVALID_FILE_HANDLE`.
Problem
I would like to ask for help with WINAPI function CreateFileMapping (), which returns constantly NULL. After GetLastError() I get 5 - "ERROR_ACCESS_DENIED 5 (0x5) Access is denied". The file has been created after CreateFile with no problem, but following CreateFileMapping never has bee succesful. ``` int MapDestFile(LPCWSTR fPath) { hDestFile = CreateFile( fPath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hSourceFile == NULL) { printf("%d\n", GetLastError()); } hDestMapFile = CreateFileMapping( hDestFile, NULL, PAGE_READWRITE, 0, 10, NULL ); if (hDestMapFile == NULL) { // here always tell error number 5 printf("%d\n", GetLastError()); } lpMapAddressDestFile = MapViewOfFile( hDestMapFile, FILE_MAP_WRITE, 0, 0, 0); if (lpMapAddressDestFile == NULL) { printf("%d\n", GetLastError()); } return 1; } ``` I would appreciate any suggestions. Thanks