Adding new bytes to memory mapped file
如何向内存映射文件添加新信息?
使用指针我可以处理现有数据,但仅限于它们当前的大小。是这样吗 ?例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | void DemoFileMapping() { HANDLE hFile = CreateFile("1.txt", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); DWORD d; char * str ="ABCDEFG"; WriteFile(hFile, str, strlen(str), &d, 0); HANDLE mapping = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, 0, 0); if (mapping) { unsigned char * buf = (unsigned char *)MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (buf) { buf[2] = 'Z'; // it works! UnmapViewOfFile(buf); } CloseHandle(mapping); } CloseHandle(hFile); } |
但是我怎样才能在当前信息中添加新信息呢?例如,将字符串扩展为"ABCDEFGHIJK"?
我想有一个解决方案,没有比文件大小更大的区域的平庸备份。
如果我正确理解您的问题 - 您问 - 在创建后可能会扩展部分(内存映射文件)。是的。但为此需要使用 ntdll api。
SECTION_EXTEND_SIZE - Dynamically extend the size of the section.
不言自明。但是 MSDN 没有解释如何扩展部分的大小。为此存在下一个 api -
也关于
但是如果部分已经映射到某个 BaseAddress - 部分的视图是否也会自动扩展?这取决于部分的地图视图。如果通过调用
但是您是否将在此使用带有 AllocationType [in] == MEM_RESERVE 的
在 win8.1 之前,如果我们想使用
1 | #define FILE_MAP_RESERVE 0x80000000 |
但由于未知原因未在 MSDN 中记录。我检查了这个标志 - 它有效(我只从 win 8.1 说)
demo/test 程序可以是下一个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | void DemoFileMapping() { HANDLE hFile = CreateFile(L"1.txt", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hFile != INVALID_HANDLE_VALUE) { HANDLE hSection; // set for demo intial size of section to 2 byte // NtCreateSection rounds this value up to the nearest multiple of PAGE_SIZE. // however this will be have effect for file size exactly, if current file size less than this value LARGE_INTEGER InitialSize = { 2 }; NTSTATUS status = NtCreateSection(&hSection, SECTION_MAP_WRITE|SECTION_MAP_READ|SECTION_EXTEND_SIZE, 0, &InitialSize, PAGE_READWRITE, SEC_COMMIT, hFile); //we can close file handle now CloseHandle(hFile); if (0 <= status) { PVOID BaseAddress = 0; SIZE_T ViewSize = 0x1000000;//reserve 16 Mb memory for example // BaseAddress = MapViewOfFile(hSection, FILE_MAP_RESERVE|FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, ViewSize); // note MEM_RESERVE if (0 <= ZwMapViewOfSection(hSection, NtCurrentProcess(), &BaseAddress, 0, 0, 0, &ViewSize, ViewUnmap, MEM_RESERVE, PAGE_READWRITE)) { LARGE_INTEGER NewSize = { 0x20001 };// some random new size (128k+1 byte) // this call extend file, section and view size if (0 <= ZwExtendSection(hSection, &NewSize)) { memset(BaseAddress, '*', NewSize.LowPart); } UnmapViewOfFile(BaseAddress); } CloseHandle(hSection); } } } |