#include "FileBuf.h"

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>

FileBuf::FileBuf()
{
	buf_ = NULL;
	len_ = 0;
}

FileBuf::~FileBuf()
{
	Free();
}

bool FileBuf::Load(const char * filename, int extra_bytes)
{
	FILE * fp = fopen(filename, "rb");
	if (fp == NULL)
		return false;

	fseek(fp,0,SEEK_END);
	len_=ftell(fp);
	fseek(fp,0,SEEK_SET);

	if (len_ == 0)
	{
		fclose(fp);
		return false;
	}

	buf_ = (unsigned char*)malloc(len_ + extra_bytes);
	if (buf_ == NULL)
	{
		fclose(fp);
		return false;
	}

	fread(buf_, 1, len_, fp);
	if (ferror(fp) != 0)
	{
		fclose(fp);
		free(buf_);
		buf_ = NULL;
		return false;
	}

	fclose(fp);

	if (extra_bytes != 0)
	{
		memset(buf_ + len_, 0, extra_bytes);
		len_ += extra_bytes;
	}
	return true;
}

void FileBuf::Free()
{
	if (buf_ != NULL)	
	{					
		free(buf_);
		buf_ = NULL;
	}

	len_ = 0;
}

void FileBuf::Clear()
{ 
	buf_ = NULL; 
}
