#include "stdafx.h"

HANDLE fileHandle, fileMapHandle;

bool mapFile(const _TCHAR* fileName, LPBYTE& ptr, DWORD& size)
{
	if (!(fileHandle = CreateFile(fileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL,
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)))
	{
		_tprintf(_T("open file %s failed error %d\n"), fileName, GetLastError());
		return false;
	}
	if (!(fileMapHandle = CreateFileMapping(fileHandle, NULL, PAGE_READWRITE, 0, 0, NULL)))		
	{
		_tprintf(_T("create file %s mapping failed error %d\n"), fileName, GetLastError());
		CloseHandle(fileHandle);
		return false;
	}
	if (!(ptr = (LPBYTE)MapViewOfFile(fileMapHandle, FILE_MAP_WRITE, 0, 0, 0)))
	{
		printf("map file %s failed error %d\n", fileName, GetLastError());
		CloseHandle(fileHandle);
		CloseHandle(fileMapHandle);
		return false;
	}
	size = GetFileSize(fileHandle, NULL);
	return true;
}


void unmapFile(LPBYTE ptr)
{
	UnmapViewOfFile(ptr);
	CloseHandle(fileHandle);
	CloseHandle(fileMapHandle);
}

void genericFind(const TCHAR* dir, HandleFileCallBack handleFileCallBack)
{
	HANDLE handle;	
	TCHAR curFileName[MAX_PATH];
	TCHAR wildFileName[MAX_PATH];
	
	WIN32_FIND_DATA ffd;

	_sntprintf(wildFileName, MAX_PATH, _T("%s\\*.*"), dir);
	handle=FindFirstFile(wildFileName, &ffd);
	if (handle==INVALID_HANDLE_VALUE)
	{
		_tprintf(_T("findfirst failed of error code =%d\n"), GetLastError());
		exit(19);
	}
	do
	{	
		if (_tcsicmp(ffd.cFileName, _T("."))!=0 && _tcsicmp(ffd.cFileName, _T(".."))!=0)
		{
			_stprintf(curFileName, _T("%s\\%s"), dir, ffd.cFileName);
			if  (GetFileAttributes(curFileName)&FILE_ATTRIBUTE_DIRECTORY)
			{
				genericFind(curFileName, handleFileCallBack);
			}
			else
			{					
				handleFileCallBack(curFileName, ffd.cFileName);
			}
		}
	}
	while (FindNextFile(handle, &ffd));	
	
	FindClose(handle);
}

		