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

82 lines
1.8 KiB
C++
Raw Normal View History

2008-01-06 23:13:01 +01:00
/*
* Copyright 2005-2007 Gerald Schmidt.
2008-01-06 23:13:01 +01:00
*
* This file is part of Xml Copy Editor.
2008-01-06 23:13:01 +01:00
*
* Xml Copy Editor is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
2008-01-06 23:13:01 +01:00
*
* Xml Copy Editor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
2008-01-06 23:13:01 +01:00
*
* You should have received a copy of the GNU General Public License
* along with Xml Copy Editor; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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
{
2008-01-06 23:13:01 +01:00
FILE *pFile;
size_t lSize;
char *buffer;
size_t result;
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
pFile = fopen ( fname, "rb" );
if ( pFile == NULL )
{
throw;
}
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
// obtain file size
fseek ( pFile , 0 , SEEK_END );
lSize = ftell ( pFile );
rewind ( pFile );
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
// allocate memory to contain the whole file:
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
//buffer = new char[lSize]; // for some reason this is much slower than malloc
buffer = ( char* ) malloc ( sizeof ( char ) *lSize );
if ( buffer == NULL )
{
throw;
}
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
// copy the file into the buffer:
result = fread ( buffer, 1, lSize, pFile );
if ( result != lSize )
{
if ( !feof ( pFile ) )
throw;
}
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
/* the whole file is now loaded in the memory buffer. */
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
// terminate
fclose ( pFile );
2007-09-08 00:25:30 +02:00
2008-01-06 23:13:01 +01:00
m_data = buffer;
m_dataLen = lSize;
2007-09-07 23:17:30 +02:00
}
BinaryFile::~BinaryFile()
{
2008-01-06 23:13:01 +01:00
//delete[] m_data;
free ( m_data );
2007-09-07 23:17:30 +02:00
}
const char *BinaryFile::getData()
{
2008-01-06 23:13:01 +01:00
return ( const char * ) m_data;
2007-09-07 23:17:30 +02:00
}
size_t BinaryFile::getDataLen()
{
2008-01-06 23:13:01 +01:00
return m_dataLen;
2007-09-07 23:17:30 +02:00
}