]> git.donarmstrong.com Git - bamtools.git/blob - src/api/internal/BamFile_p.cpp
3927d302879388516c1093eafe440f0ed963a3c9
[bamtools.git] / src / api / internal / BamFile_p.cpp
1 // ***************************************************************************
2 // BamFile_p.cpp (c) 2011 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 7 October 2011 (DB)
6 // ---------------------------------------------------------------------------
7 // Provides BAM file-specific IO behavior
8 // ***************************************************************************
9
10 #include <api/internal/BamFile_p.h>
11 using namespace BamTools;
12 using namespace BamTools::Internal;
13
14 #include <cstdio>
15 #include <iostream>
16 using namespace std;
17
18 BamFile::BamFile(const string& filename)
19     : ILocalIODevice()
20     , m_filename(filename)
21 { }
22
23 BamFile::~BamFile(void) { }
24
25 void BamFile::Close(void) {
26     if ( IsOpen() ) {
27         m_filename.clear();
28         ILocalIODevice::Close();
29     }
30 }
31
32 bool BamFile::IsRandomAccess(void) const {
33     return true;
34 }
35
36 bool BamFile::Open(const IBamIODevice::OpenMode mode) {
37
38     // make sure we're starting with a fresh file stream
39     Close();
40
41     // attempt to open FILE* depending on requested openmode
42     if ( mode == IBamIODevice::ReadOnly )
43         m_stream = fopen(m_filename.c_str(), "rb");
44     else if ( mode == IBamIODevice::WriteOnly )
45         m_stream = fopen(m_filename.c_str(), "wb");
46     else {
47         SetErrorString("BamFile::Open", "unknown open mode requested");
48         return false;
49     }
50
51     // check that we obtained a valid FILE*
52     if ( m_stream == 0 ) {
53         const string message_base = string("could not open file handle for ");
54         const string message = message_base + ( (m_filename.empty()) ? "empty filename" : m_filename );
55         SetErrorString("BamFile::Open", message);
56         return false;
57     }
58
59     // store current IO mode & return success
60     m_mode = mode;
61     return true;
62 }
63
64 bool BamFile::Seek(const int64_t& position) {
65     BT_ASSERT_X( m_stream, "BamFile::Seek() - null stream" );
66     return ( fseek64(m_stream, position, SEEK_SET) == 0 );
67 }