(windows)内存映射文件

1.运行结果图

2。程序代码

#include <Windows.h>
#include "CharNumber.h"

INT WINAPI wWinMain(
	HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPWSTR lpCmdLine,
	int nCmdShow)
{
	// show picture -- 1.1
	MessageBoxW(NULL,L"begin window",L"window",MB_OK);
	//1.create file and get the file handle.
	HANDLE hTestFile=CreateFileW(
		L"C:\\testFile.txt",
		GENERIC_READ|GENERIC_WRITE,
		FILE_SHARE_READ|FILE_SHARE_WRITE,
		NULL,
		OPEN_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		0);
	if(hTestFile == INVALID_HANDLE_VALUE)
	{
		MessageBoxW(NULL,L"create file failed",L"window",MB_OK);
	}
	//2.create file mapping and get the file mapping handle.
	HANDLE hTestFileMapping=CreateFileMappingW(
		hTestFile,
		NULL,
		PAGE_READWRITE,
		0,
		65536,
		L"TestFileMapping");
	if(hTestFileMapping == INVALID_HANDLE_VALUE)
	{
		MessageBoxW(NULL,L"create file mapping failed",L"window",MB_OK);
	}
	//3.get the system info and get the system allocation granularity
	SYSTEM_INFO sys_info;
	GetSystemInfo(&sys_info);
	//4.create file mapping view and the the view base address.
	LPVOID pVoidBaseAddress=MapViewOfFile(
		hTestFileMapping,
		FILE_MAP_ALL_ACCESS,
		0,
		0,
		sys_info.dwAllocationGranularity);
	if(pVoidBaseAddress == NULL)
	{
		MessageBoxW(NULL,L"mapping view of file failed.",L"window",MB_OK);
	}
	//5.write data to file. -- show picture 1.2 
	ZeroMemory(pVoidBaseAddress,sys_info.dwAllocationGranularity);
	CHAR *pCharBaseAddress=reinterpret_cast<CHAR*>(pVoidBaseAddress);
	for(INT number=0;number<10;number++)
	{
		*pCharBaseAddress=static_cast<char>(number+48);
		pCharBaseAddress++;
	}
	//6.read data from file. -- show picture 1.3
	pCharBaseAddress=reinterpret_cast<CHAR*>(pVoidBaseAddress);
	WCHAR *wpStr=new WCHAR[11];
	memset(wpStr,0,sizeof(22));
	if(MultiByteToWideChar(
		CP_ACP,
		MB_PRECOMPOSED,
		pCharBaseAddress,
		11,
		wpStr,
		11))
	{
		MessageBoxW(NULL,wpStr,L"window",MB_OK);
	}
	else
	{
		MessageBoxW(NULL,L"ansi to unicode byte error",L"window",MB_OK);
	}
	//7.flush data to file.
	FlushViewOfFile(pVoidBaseAddress,10);
	//release all resources.
	UnmapViewOfFile(pVoidBaseAddress);
	CloseHandle(hTestFileMapping);
	CloseHandle(hTestFile);
	//show picture -- 1.4
	MessageBoxW(NULL,L"end window",L"window",MB_OK);
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

当当小螳螂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值