Answer the question
In order to leave comments, you need to log in
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;
}
#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;
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question