xml-copy-editor-code/src/binaryfile.cpp

63 lines
1.1 KiB
C++
Raw Normal View History

2007-09-07 23:17:30 +02:00
#include "binaryfile.h"
#include <stdexcept>
2007-09-08 00:25:30 +02:00
BinaryFile::BinaryFile ( const char *fname ) : m_data ( 0 ), m_dataLen ( 0 )
2007-09-07 23:17:30 +02:00
{
2007-09-08 00:25:30 +02:00
FILE *pFile;
size_t lSize;
char *buffer;
size_t result;
pFile = fopen ( fname, "rb" );
if ( pFile == NULL )
{
throw;
}
// obtain file size
fseek ( pFile , 0 , SEEK_END );
lSize = ftell ( pFile );
rewind ( pFile );
// allocate memory to contain the whole file:
//buffer = new char[lSize]; // for some reason this is much slower than malloc
buffer = ( char* ) malloc ( sizeof ( char ) *lSize );
if ( buffer == NULL )
{
throw;
}
// copy the file into the buffer:
result = fread ( buffer, 1, lSize, pFile );
if ( result != lSize )
{
if ( !feof ( pFile ) )
throw;
}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose ( pFile );
m_data = buffer;
m_dataLen = lSize;
2007-09-07 23:17:30 +02:00
}
BinaryFile::~BinaryFile()
{
2007-09-08 00:25:30 +02:00
//delete[] m_data;
free ( m_data );
2007-09-07 23:17:30 +02:00
}
const char *BinaryFile::getData()
{
2007-09-08 00:25:30 +02:00
return ( const char * ) m_data;
2007-09-07 23:17:30 +02:00
}
size_t BinaryFile::getDataLen()
{
2007-09-08 00:25:30 +02:00
return m_dataLen;
2007-09-07 23:17:30 +02:00
}