00001 #include "RawFile/raw_ofstream.h" 00002 #include "RawFile/RawFileTools.h" 00003 #include <cstdlib> 00004 00005 #define MAX_RAWFILE_SiZE 2000000000 //an approximate value, not exactly 00006 00007 //static data members 00008 int raw_ofstream::_nHandler = 0; 00009 raw_ofstream* raw_ofstream::_instance = 0; 00010 pthread_mutex_t raw_ofstream::_pthread_lock = PTHREAD_MUTEX_INITIALIZER; 00011 00012 00013 raw_ofstream* raw_ofstream::instance(const std::string& fname) 00014 { 00015 lock(); 00016 00017 if ( _instance == 0 ) { 00018 _instance = new raw_ofstream(fname); 00019 } 00020 00021 ++_nHandler; 00022 00023 unlock(); 00024 00025 return _instance; 00026 } 00027 00028 void raw_ofstream::release() 00029 { 00030 lock(); 00031 00032 if ( _nHandler > 0 && --_nHandler == 0 ) { 00033 delete _instance; 00034 _instance = 0; 00035 } 00036 00037 unlock(); 00038 } 00039 00040 raw_ofstream::raw_ofstream(const std::string& fname) 00041 : m_nevt(0), 00042 m_nfile(0), 00043 m_fname(fname) 00044 { 00045 init_fstream(); 00046 } 00047 00048 raw_ofstream::~raw_ofstream() 00049 { 00050 this->close(); 00051 } 00052 00053 int raw_ofstream::write_event(const char* pbuf, int size) 00054 { 00055 uint32_t fsize = tellp(); 00056 if ( fsize >= MAX_RAWFILE_SiZE ) { 00057 this->close(); 00058 init_fstream(); 00059 } 00060 00061 m_dataSeparatorRecord.setDataBlockNumber(++m_nevt); 00062 m_dataSeparatorRecord.setDataBlockSize(size); 00063 00064 (*this) << m_dataSeparatorRecord; 00065 std::ofstream::write(pbuf, size); 00066 00067 return m_nfile; 00068 } 00069 00070 void raw_ofstream::close() 00071 { 00072 if ( is_open() ) { 00073 m_fileEndRecord.setEventsInFile(m_nevt); 00074 m_nevt = 0; 00075 00076 (*this) << m_fileEndRecord; 00077 std::ofstream::close(); 00078 00079 std::cout << "[RawFile] Finished writing file: " << real_fname() << std::endl; 00080 } 00081 } 00082 00083 void raw_ofstream::init_fstream() 00084 { 00085 ++m_nfile; 00086 00087 std::string fname = real_fname(); 00088 00089 if ( access( fname.c_str(), F_OK ) == 0 ) { 00090 std::cerr << "[RawFile] Attempt to create an exist file: " << fname << std::endl; 00091 exit(1); 00092 } 00093 00094 std::cout << "[RawFile] Creating a new file: " << real_fname() << std::endl; 00095 open( fname.c_str(), std::ios::binary ); 00096 00097 (*this) << m_fileStartRecord << m_fileNameStrings << m_runParametersRecord; 00098 } 00099 00100 std::string raw_ofstream::real_fname() 00101 { 00102 std::string fname = m_fname; 00103 00104 if ( m_nfile > 1 ) { 00105 fname += ".part" + RawFileTools::itoa( m_nfile ); 00106 } 00107 00108 return fname; 00109 }