#include "stdafx.h" #include <Windows.h> #include <stdio.h>
int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile = CreateFile(TEXT("test.dat"), GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); DWORD dwFileSize = GetFileSize(hFile, NULL); DWORD dwWritten; printf("文件大小: %d\n", dwFileSize);
if (dwFileSize == 0) { char str[100]; strcpy_s(str, "Creates or opens a named or unnamed file mapping object for a specified file."); WriteFile(hFile, str, sizeof(str), &dwWritten, NULL); dwFileSize = GetFileSize(hFile, NULL); } HANDLE hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwFileSize, NULL); LPSTR lpData = (LPSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, dwFileSize); puts(lpData); // 只修改内存中的字符串 (最后会被自动写入文件) lpData[8] = 'O'; lpData[9] = 'R'; //FlushViewOfFile(lpData + 8, 2); // 立即写入文件
UnmapViewOfFile(lpData); CloseHandle(hMapFile);
CloseHandle(hFile); return 0; }
|