File Mapping的簡單使用

來源:互聯網
上載者:User

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 />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.