#include "stdafx.h"
#include "Mfcfile.h"
#include <tchar.h>


CFile::CFile():FileLength(0)
{
	hFile=NULL;
}

CFile::~CFile()
{
	if(hFile)
		CloseHandle(hFile);
}

BOOL CFile::Create(LPCTSTR lpFileName)
{
	hFile=CreateFile(lpFileName,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,0,0);
	if(hFile==INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);
		return FALSE;
	}
	return TRUE;
} 

BOOL CFile::Open(LPCTSTR lpFileName)
{
	hFile=CreateFile(lpFileName,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
	//hFile=CreateFile(lpFileName,GENERIC_READ|GENERIC_WRITE,NULL,NULL,OPEN_EXISTING,0,0);
	if(hFile==INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);
		return FALSE;
	}
	DWORD  FileSizeHigh;
	DWORD  FileSizeLow=GetFileSize(hFile,&FileSizeHigh);
	FileLength=FileSizeHigh+FileSizeLow;
	return TRUE;
}

BOOL CFile::Read(LPVOID buffer,DWORD ReadNumber)
{
	if(hFile)
	{
		DWORD iRead;
		if(ReadFile(hFile,buffer,ReadNumber,&iRead,NULL))
		{		
			if(ReadNumber!=iRead)
			{
				return FALSE;
			}
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	return FALSE;
}

void CFile::Close()
{
	if(hFile)
		CloseHandle(hFile);
	hFile=NULL;
}

DWORD CFile::GetLength()
{
	if(hFile)
		return FileLength;
	else 
		return 0;
}

void CFile::SetEnd()
{
	SetFilePointer(hFile,0,0,FILE_END);
} 

void CFile::SetBegin()
{
	if(hFile)
		SetFilePointer(hFile,0,0,FILE_BEGIN);
} 

void CFile::Seek(LONG nMove,DWORD Method)//FILE_BEGIN//FILE_CURRENT//FILE_END
{
	if(hFile)
	{
		LONG iMove=0;
		SetFilePointer(hFile,nMove,&iMove,Method);
	}
} 

BOOL CFile::Write(LPVOID buffer,DWORD WriteNumber)
{
	if(hFile)
	{
		DWORD iWrite;
		if(WriteFile(hFile,buffer,WriteNumber,&iWrite,NULL))
		{
			if(WriteNumber!=iWrite)
				return FALSE;
		}
		return TRUE;
	}
	return FALSE;
}


