File mapping

Edit file in place:

    HANDLE hFile = CreateFile("dst", GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, nullptr);
    char *pContent = static_cast<char *>(MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0));

// Reverse the content. reverse(pContent, pContent
+ GetFileSize(hFile, nullptr)); // Restore the '\n'. (It is "\r\n" in windows.) char *p = pContent; while ((p = strstr(p, "\n\r")) != NULL) { swap(p[0], p[1]); } UnmapViewOfFile(pContent); CloseHandle(hFileMap); CloseHandle(hFile);

  Change file at hard disk, no memory is used.

  This trick is used for very large file which unnecessary to load it all to memory.

 

Share data among processes:

#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    // Run two instances, the second instance will get data from first one.
    // First: reserve a address space.
    HANDLE hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 256, "fooWin32");
    const DWORD err = GetLastError();
    // Second: Allocate from page swapping file.
    char *data = static_cast<char *>(MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0));

    switch (err)
    {
    case S_OK:
        // Non-instance exists, create data.
        strcpy(data, "1234");
        break;
    case ERROR_ALREADY_EXISTS:
        // Get shared data.
        cout <<"exists: " <<data <<endl;
        break;
    default:
        cerr <<"unknown." <<endl;
        break;
    }

    UnmapViewOfFile(data);
    CloseHandle(hFileMap);
    Sleep(INFINITE);
    return 0;
}
posted @ 2012-10-12 18:03  walfud  阅读(522)  评论(0编辑  收藏  举报