1 // ***************************************************************************
2 // BamPipe_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/writing of piped BAM files (stdin/stdout)
8 // ***************************************************************************
10 #include <api/internal/BamPipe_p.h>
11 using namespace BamTools;
12 using namespace BamTools::Internal;
17 BamPipe::BamPipe(void)
22 BamPipe::~BamPipe(void) {
26 void BamPipe::Close(void) {
29 if ( !IsOpen() ) return;
31 // flush & close FILE*
36 m_mode = IBamIODevice::NotOpen;
40 bool BamPipe::IsRandomAccess(void) const {
44 bool BamPipe::Open(const IBamIODevice::OpenMode mode) {
46 // make sure we're starting with a fresh pipe
49 // open stdin/stdout depending on requested openmode
50 if ( mode == IBamIODevice::ReadOnly )
51 m_stream = freopen(0, "rb", stdin);
52 else if ( mode == IBamIODevice::WriteOnly )
53 m_stream = freopen(0, "wb", stdout);
55 SetErrorString("BamPipe ERROR - unsupported device mode");
59 // check that we obtained a valid FILE*
60 if ( m_stream == 0 ) {
61 string error = "BamPipe ERROR - could not open handle on ";
62 error += ( (mode == IBamIODevice::ReadOnly) ? "stdin" : "stdout" );
63 SetErrorString(error);
67 // store current IO mode & return success
72 size_t BamPipe::Read(char* data, const unsigned int numBytes) {
73 BT_ASSERT_X( m_stream, "BamPipe::Read() - null stream" );
74 BT_ASSERT_X( (m_mode == IBamIODevice::ReadOnly), "BamPipe::Read() - device not in read-only mode");
75 return fread(data, sizeof(char), numBytes, m_stream);
78 bool BamPipe::Seek(const int64_t& position) {
79 (void)position; // suppress compiler warning about unused variable
80 return false; // seeking not allowed in pipe
83 int64_t BamPipe::Tell(void) const {
84 BT_ASSERT_X( m_stream, "BamPipe::Tell() - null stream" );
85 return ftell64(m_stream);
88 size_t BamPipe::Write(const char* data, const unsigned int numBytes) {
89 BT_ASSERT_X( m_stream, "BamPipe::Write() - null stream" );
90 BT_ASSERT_X( (m_mode == IBamIODevice::WriteOnly), "BamPipe::Write() - device not in write-only mode" );
91 return fwrite(data, sizeof(char), numBytes, m_stream);