#ifndef FILEIO_H
#define FILEIO_H

#include <stdexcept>
#include <string>

class CFile
{
public:
	CFile( const std::string& filename, bool read )
	{
		m_file = fopen( filename.c_str(), read? "rb" : "wb" );
		if (!m_file)
			throw std::runtime_error("Unable to open file: " + filename);
	}
	~CFile()
	{
		fclose( m_file );
	}

	void Read( void * pBuf, size_t bufSize )
	{
		if (bufSize != fread( pBuf, 1, bufSize, m_file ))
			throw std::runtime_error("Error reading file");
	}

	void Write( const void * pBuf, size_t bufSize )
	{
		if (bufSize != fwrite( pBuf, 1, bufSize, m_file ))
			throw std::runtime_error("Error writing file");
	}

	fpos_t GetPos()
	{
		fpos_t out;
		if (0 != fgetpos( m_file, &out ))
			throw std::runtime_error("fgetpos failed");
		return out;
	}

	void SetPos( fpos_t pos )
	{
		if (0 != fsetpos( m_file, &pos ))
			throw std::runtime_error("fsetpos failed");
	}

	void Seek( long pos, int whence )
	{
		if (0 != fseek( m_file, pos, whence ))
			throw std::runtime_error("fseek failed");
	}

private:
	CFile( const CFile& );
	CFile& operator=( const CFile& );

	FILE * m_file;
};

#endif
