16,548
社区成员




#include <windows.h>
#include <stdio.h>
#include <conio.h>
#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process");
TCHAR szFileName[]=TEXT("xxx.txt");
void main()
{
HANDLE hMapFile, hFile;
LPCTSTR pBuf;
hFile = CreateFile(szFileName, // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
{
printf("Could not open file (error %d)\n", GetLastError());
return 0;
}
hMapFile = CreateFileMapping(
hFile,
NULL, // default security
PAGE_READWRITE, // read/write access
0, // max. object size
BUF_SIZE, // buffer size
szName); // name of mapping object
if (hMapFile == NULL || hMapFile == INVALID_HANDLE_VALUE)
{
printf("Could not create file mapping object (%d).\n",
GetLastError());
return;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
printf("Could not map view of file (%d).\n",
GetLastError());
return;
}
//在这里访问pBuf,就是访问文件
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
CloseHandle(hFile);
}