1、建立一個檔案對應物件,並寫入一些內容:
#include <stdio.h><br />#include <conio.h><br />#include <windows.h></p><p>int main(void)<br />{<br />HANDLE hMapFile;<br />//建立一個名為leng_que、大小為1024Byte且可讀寫的檔案對應物件<br />hMapFile = CreateFileMapping(NULL, NULL, PAGE_READWRITE, 0, 1024, "leng_que");<br />if (hMapFile == NULL)<br />{<br />printf("無法建立檔案對應物件");<br />getch();<br />return -1;<br />}</p><p>LPVOID lpMapAddress;<br />lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);<br />if (lpMapAddress == NULL)<br />{<br />printf("無法對應檔視圖");<br />getch();<br />return -2;<br />}</p><p>strcpy((char*)lpMapAddress, "Hello,這個對應檔是我建立的哦!");<br />UnmapViewOfFile(lpMapAddress);</p><p>printf("已經建立好了對應檔,並且寫入了一些內容,正在等待其它進程的讀取...");<br />getch();</p><p>CloseHandle(hMapFile);</p><p>return 0;<br />}<br />
2、開啟一個檔案對應物件,並讀取其中的內容:
#include <stdio.h><br />#include <conio.h><br />#include <windows.h></p><p>int main(void)<br />{<br />HANDLE hMapFile;<br />//開啟一個名為leng_que的檔案對應物件<br />hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, "leng_que");<br />if (hMapFile == NULL)<br />{<br />printf("無法開啟檔案對應物件");<br />getch();<br />return -1;<br />}</p><p>LPVOID lpMapAddress;<br />lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);<br />if (lpMapAddress == NULL)<br />{<br />printf("無法對應檔視圖");<br />getch();<br />return -2;<br />}</p><p>printf("讀取到的內容:%s", lpMapAddress);</p><p>UnmapViewOfFile(lpMapAddress);<br />CloseHandle(hMapFile);</p><p>getch();<br />return 0;<br />}<br />