1 // ***************************************************************************
2 // BamFile_p.cpp (c) 2011 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 8 September 2011 (DB)
6 // ---------------------------------------------------------------------------
7 // Provides reading of local BAM files
8 // ***************************************************************************
10 #include <api/internal/BamFile_p.h>
11 using namespace BamTools;
12 using namespace BamTools::Internal;
17 BamFile::BamFile(const string& filename)
20 , m_filename(filename)
23 BamFile::~BamFile(void) {
27 void BamFile::Close(void) {
33 // flush & close FILE*
38 m_mode = IBamIODevice::NotOpen;
43 bool BamFile::IsRandomAccess(void) const {
47 bool BamFile::Open(const IBamIODevice::OpenMode mode) {
49 // make sure we're starting with a fresh file stream
52 // attempt to open FILE* depending on requested openmode
53 if ( mode == IBamIODevice::ReadOnly )
54 m_stream = fopen(m_filename.c_str(), "rb");
55 else if ( mode == IBamIODevice::WriteOnly )
56 m_stream = fopen(m_filename.c_str(), "wb");
58 SetErrorString("BamFile ERROR - unknown device open mode");
62 // check that we obtained a valid FILE*
63 if ( m_stream == 0 ) {
64 string error = "BamFile ERROR - could not open handle on ";
65 error += ( (m_filename.empty()) ? "empty filename" : m_filename );
66 SetErrorString(error);
70 // store current IO mode & return success
75 size_t BamFile::Read(char* data, const unsigned int numBytes) {
76 BT_ASSERT_X( m_stream, "BamFile::Read() - null stream" );
77 BT_ASSERT_X( (m_mode == IBamIODevice::ReadOnly), "BamFile::Read() - device not in read-only mode");
78 return fread(data, sizeof(char), numBytes, m_stream);
81 bool BamFile::Seek(const int64_t& position) {
82 BT_ASSERT_X( m_stream, "BamFile::Seek() - null stream" );
83 return ( fseek64(m_stream, position, SEEK_SET) == 0);
86 int64_t BamFile::Tell(void) const {
87 BT_ASSERT_X( m_stream, "BamFile::Tell() - null stream" );
88 return ftell64(m_stream);
91 size_t BamFile::Write(const char* data, const unsigned int numBytes) {
92 BT_ASSERT_X( m_stream, "BamFile::Write() - null stream" );
93 BT_ASSERT_X( (m_mode == IBamIODevice::WriteOnly), "BamFile::Write() - device not in write-only mode" );
94 return fwrite(data, sizeof(char), numBytes, m_stream);