// TestFileMap.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
char* strFilePath = "C:\\Documents and Settings\\wangwei_b\\My Documents\\Visual Studio 2008\\Projects\\TestFileMap\\Debug\\test.txt";
HANDLE m_handle_file = CreateFile(strFilePath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(m_handle_file == INVALID_HANDLE_VALUE)
{
CloseHandle(m_handle_file);
return 0;
}
//创建文件映射对象
HANDLE m_handle_map = CreateFileMapping(m_handle_file,NULL,PAGE_READWRITE,0,1024*1024*1024,NULL);
if(m_handle_map == NULL)
{
CloseHandle(m_handle_map);
return 0;
}
//获得系统分配的粒度
SYSTEM_INFO m_systeminfo;
GetSystemInfo(&m_systeminfo);
DWORD dwGran = m_systeminfo.dwAllocationGranularity;
DWORD dwFileSizeHigh;
__int64 qwFileSize = GetFileSize(m_handle_file,&dwFileSizeHigh);
qwFileSize = 1024*1024*1024;
qwFileSize |= (((__int64)dwFileSizeHigh) << 32);
CloseHandle(m_handle_file);
//偏移地址
__int64 qwFileOfSet = 0;
DWORD dwBlocByte = dwGran;
while(qwFileSize > 0)
{
if( qwFileSize < dwBlocByte)
{
dwBlocByte = (DWORD)qwFileSize;//如果小于则为实际大小
}
//映射视图
LPBYTE lpMapAddress = (LPBYTE)MapViewOfFile(m_handle_map,FILE_MAP_ALL_ACCESS,(DWORD)(qwFileOfSet >> 32),(DWORD)(qwFileOfSet & 0xFFFFFFFF),dwBlocByte);
if(lpMapAddress == NULL)
{
CloseHandle(m_handle_map);
return 0;
}
//对映射视图进行访问
for(DWORD i = 0; i < dwBlocByte; i++)
{
*(lpMapAddress+i) = 's';
}
//撤销文件映像
UnmapViewOfFile(lpMapAddress);
qwFileOfSet += dwBlocByte;
qwFileSize -= dwBlocByte;
}
CloseHandle(m_handle_map);
return 0;
}
运行后效果:将debug目录下的test.log改写成1G的文件, 内容全部是's'