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;
}