Search code examples
cwindowsmmapcreatefile

windows c : failed to create mmap of a file


I need to create mmap of a file. Since windows does not support mmap, i tried MapViewOfFile() method. But this fails.

Here's my code :

char template[1024];
snprintf(template, sizeof(template) / sizeof(char), "%s", "C:\\Users\\Ijas\\Downloads\\ijas.txt");

HANDLE  hfile = CreateFile(template, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);

if (hfile == INVALID_HANDLE_VALUE)
{
    fprintf(stderr, "CreateFile() error 0x%08x \n", GetLastError());
    return NULL;
}

HANDLE map_handle = CreateFileMapping(hfile, NULL, PAGE_READWRITE | SEC_RESERVE, 0, 0, 0);
if (map_handle == NULL)
{
    fprintf(stderr, "CreateFileMapping() error 0x%08x\n", GetLastError());
    CloseHandle(hfile);
    return NULL;

}

sp = (char*)MapViewOfFile(map_handle, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);

if (sp->buffer == NULL)
{
    fprintf(stderr, "MapViewOfFile() error 0x%08x\n", GetLastError());
    CloseHandle(hMapFile);
    CloseHandle(hfile);
    return NULL;
}

Output :

CreateFile() error 0x00000003

Hint : template is an existing file.

Anything wrong in my code? Please help me out?


Solution

  • As discussed in comments, with various possibilities of try-and-hit, the problem seems to be with Unicode and Ansi. template is declared as char* but is passed to CreateFile which by default calls CreateFileW. If OP would have compiled the code with C++ compiler, the compiler would have complained about this but with C compiler, it just relied on the coder's intellect.

    CreateFileA expects const char* whereas CreateFileW expects const wchar_t*