ファイルマッピング

2411 ワード

FileMap.h
#include "..\include\error_type.h"
#include <string>
#include <iostream>
#include <windows.h>

using namespace std;

class FileMap
{
public:
	FileMap(const string& path, const string& name);
	~FileMap();
	file_map_crate_mode GetMapMode();
	void TextData();

private:
	HANDLE					m_hFile;
	HANDLE					m_hFileMapping;
	PBYTE					m_pMapBase;
	string					m_path;
	string					m_name;
	file_map_crate_mode		m_craete_mode;
};
 
  

FileMap.cpp

#include "FileMap.h"
FileMap::FileMap(const string& path, const string& name)
{
	DWORD nRet = error_ok;
	m_craete_mode = file_map_open;
	m_hFileMapping = OpenFileMappingA(FILE_MAP_READ, FALSE, name.c_str());
	if(NULL == m_hFileMapping)
	{
		m_craete_mode = file_map_create;
		cout << "open file maping failed. creating file mapping ->" << name << endl; 
		m_hFile = CreateFileA(path.c_str(), GENERIC_READ, PAGE_READONLY, NULL, OPEN_EXISTING, NULL, NULL);
		if(INVALID_HANDLE_VALUE == m_hFile)
		{
			cout << "create file failed." << GetLastError() << endl;
			nRet = error_create_file;
		}
		else
		{
			DWORD nSize = 0;
			nSize = GetFileSize(m_hFile, NULL);
			m_hFileMapping = CreateFileMappingA(m_hFile, NULL, PAGE_READONLY, 0, nSize, name.c_str());
			if(NULL == m_hFileMapping)
			{
				cout << "create file mapping failed.
"; nRet = error_create_file_mapping; } } } else { cout << "open file mapping success.
"; } if (NULL != m_hFileMapping) { m_name = name; m_path = path; m_pMapBase = (PBYTE)MapViewOfFile(m_hFileMapping, FILE_MAP_READ, 0, 0, 0); } } file_map_crate_mode FileMap::GetMapMode() { return m_craete_mode; } void FileMap::TextData() { cout << "
file map data:
"; cout << m_pMapBase << endl; } FileMap::~FileMap() { UnmapViewOfFile(m_pMapBase); CloseHandle(m_hFileMapping); CloseHandle(m_hFile); }

main.cpp
#include "FileMap.h"

int main(int argc, char* argv[])
{
	if(argc >=3)
	{
		FileMap map1(argv[1], argv[2]);
		map1.TextData();
	}
	else
	{
		cout << "usage:pro.exe shr_name shr_path" << endl;
	}
	system("pause");
	return 0;
}