-2

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.
  • The output does not match the code. In fact, the code does not even compile. What is `FILE_MAP_ACCESS`? – IInspectable Aug 04 '15 at 15:51
  • 2
    Your error checking and handling is very sloppy. CreateFileMapping() returns NULL when it fails. Using GetLastError() after you've used printf() is fundamentally wrong. Using PAGE_EXECUTE_READWRITE on a text file does not make any sense. – Hans Passant Aug 04 '15 at 16:16

1 Answers1

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.

marcinj
  • 44,446
  • 9
  • 70
  • 91