G
G
German2019-04-09 19:23:38
C++ / C#
German, 2019-04-09 19:23:38

How to read and write to a file using file memory mapping?

It is necessary to organize communication between two programs.
Control application:

#include <conio.h>
#include <iostream>
#include <Windows.h>

using namespace std;

int main(int argc, char* argv[])
{
  HANDLE fileHandle = CreateFile(
    L"IPC.txt",
    GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE | FILE_SHARE_READ,
    NULL,
    OPEN_ALWAYS,
    NULL,
    NULL
  );
  if (!fileHandle) { cout << "Create file failed\n"; return 1; }
  HANDLE fileMappingHandle = CreateFileMapping(
    fileHandle,
    NULL,
    PAGE_READWRITE,
    NULL,
    NULL,
    L"MyMappingFile"
  );
  if (!fileMappingHandle) { cout << "Create file mapping failed\n"; return 1; }

  LPVOID mapViewOfFileAddr = MapViewOfFile(
    fileMappingHandle,
    FILE_MAP_ALL_ACCESS,
    NULL,
    NULL,
    65536
  );
  if (!mapViewOfFileAddr) { cout << "Map view failed\n"; return 1; }
  cout << "Share success\n";
  _getch();

  UnmapViewOfFile(mapViewOfFileAddr);
  CloseHandle(fileHandle);
  CloseHandle(fileMappingHandle);
  return 0;
}

And an application that needs to read and sometimes write
#include <iostream>
#include <Windows.h>

using namespace std;

int main(int argc, char* argv[])
{
  HANDLE openFileMapping = OpenFileMapping(
    GENERIC_READ | GENERIC_WRITE,
    FALSE,
    L"MyMappingFile"
  );
  if (!openFileMapping) { cout << "Open file mapping failed\n"; return 1; }

  LPVOID mapViewOfFileAddr = MapViewOfFile(
    openFileMapping,
    FILE_MAP_ALL_ACCESS,
    NULL,
    NULL,
    65536
  );
  if (!mapViewOfFileAddr) { cout << "Map view of file failed\n"; return 1; }
  cout << "Reading\n";
  CloseHandle(openFileMapping);
  return 0;
}

Everything seems to be ready and working.
How to read/write data now?
In the first application, you need to work, as I understand it, just with a file.
And what to do in the second application for reading / writing data?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vanyamba-electronics, 2019-04-09
@vanyamba-electronics

You have mapped the file to memory, and now you can simply write data to memory at this address. And they will be written to a file.
This is the same mechanism as virtual memory. There is a virtual memory file, and some of its parts are loaded into RAM.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question