// FileStream.cpp: implementation of the CFileStream class.
//
//////////////////////////////////////////////////////////////////////

#include "FileStream.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CFileStream::CFileStream()
{
	m_pszClassName = "CFileStream";

	m_pFile = NULL;
}

CFileStream::~CFileStream()
{
	Close();
}

bool CFileStream::Open(LPSTR lpszFileName, MODE mode)
{
	char* pszMode;
	switch (mode)
	{
		case CREATE:
			pszMode = "wb";
			break;

		case READONLY:
			pszMode = "rb";
			break;

		case READWRITE:
			pszMode = "r+b";
			break;
	}

	///////////////////////////////////////////////////////////////////////////
	m_pFile = fopen(lpszFileName, pszMode);
	if (!m_pFile)
		return false;

	return true;
}

void CFileStream::Close()
{
	if (m_pFile)
	{
		fclose(m_pFile);
		m_pFile = NULL;
	}
}

size_t CFileStream::Read(void *buffer, size_t size, size_t count)
{
	return fread(buffer, size, count, m_pFile);
}

size_t CFileStream::ReadString(void *buffer)
{
	BYTE length;
	Read(&length, sizeof(BYTE), 1);

	if (length)
	{
		fread(buffer, sizeof(BYTE), length, m_pFile);

		char* pszBuffer = (char*) buffer;
		pszBuffer[length] = 0;
	}

	return length;
}

size_t CFileStream::Write(void *buffer, size_t size, size_t count)
{
	return fwrite(buffer, size, count, m_pFile);
}

size_t CFileStream::WriteString(void *buffer)
{
	BYTE length = 0;
	if (buffer)
	{
		char* pszBuffer = (LPSTR) buffer;
		length = strlen(pszBuffer);

		fwrite(&length, sizeof(BYTE), 1, m_pFile);
		fwrite(pszBuffer, sizeof(BYTE), length, m_pFile);
	}
	else
	{
		fwrite(&length, sizeof(BYTE), 1, m_pFile);
	}

	return length;
}

int CFileStream::ReadChar()
{
	return fgetc(m_pFile);
}

int CFileStream::WriteChar(int c)
{
	return fputc(c, m_pFile);
}

int CFileStream::Seek(long offset, int origin)
{
	return fseek(m_pFile, offset, origin);
}

long CFileStream::Position()
{
	return ftell(m_pFile);
}
