Shouldn’t you use OPEN_EXISTING instead of OPEN_ALWAYS when calling CreateFile?
If the file doesn’t exist, OPEN_EXISTING will return an error code. OPEN_ALWAYS will create a new file if it doesn’t already exist, you then call GetFileSize and retrieve the size of the empty file and attempt to map the empty file into memory.
MSDN (CreateFileMapping function’s fourth parameter):
The low-order DWORD of the maximum size of the file mapping object.
If this parameter and dwMaximumSizeHigh are 0 (zero), the maximum size of the file mapping object is equal to the current size of the file that hFile identifies.
An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should test for files with a length of 0 (zero) and reject those files.
^ “Applications should test for files with a length of 0 (zero) and reject those files.”
CreateFileMapping & MapViewOfFile will both fail if CreateFile creates a new file. CreateFileMapping fails because the file size of the newly created file is zero and MapViewOfFile fails because CreateFileMapping returns NULL to its handle after failing. CreateFileMapping returns ERROR_FILE_INVALID(1006) and MapViewOfFile returns ERROR_INVALID_HANDLE(6). Change CreateFile’s dwCreationDisposition parameter to OPEN_EXISTING.