Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:22:31

0001 #include "binary_ofstream.h"
0002 
0003 #include <cstdio>
0004 #include <iostream>
0005 #include <cstdint>
0006 
0007 struct binary_ofstream_error {};
0008 
0009 binary_ofstream::binary_ofstream(const char* name) : file_(nullptr) { init(name); }
0010 
0011 binary_ofstream::binary_ofstream(const std::string& name) : file_(nullptr) { init(name.c_str()); }
0012 
0013 void binary_ofstream::init(const char* name) {
0014   file_ = fopen(name, "wb");
0015   if (file_ == nullptr) {
0016     std::cout << "file " << name << " cannot be opened for writing" << std::endl;
0017     throw binary_ofstream_error();
0018   }
0019 }
0020 
0021 binary_ofstream::~binary_ofstream() { close(); }
0022 void binary_ofstream::close() {
0023   if (file_ != nullptr)
0024     fclose(file_);
0025   file_ = nullptr;
0026 }
0027 
0028 binary_ofstream& binary_ofstream::operator<<(char n) {
0029   fputc(n, file_);
0030   return *this;
0031 }
0032 binary_ofstream& binary_ofstream::operator<<(unsigned char n) {
0033   fputc(n, file_);
0034   return *this;
0035 }
0036 
0037 binary_ofstream& binary_ofstream::operator<<(short n) {
0038   fwrite(&n, sizeof(n), 1, file_);
0039   return *this;
0040 }
0041 binary_ofstream& binary_ofstream::operator<<(unsigned short n) {
0042   fwrite(&n, sizeof(n), 1, file_);
0043   return *this;
0044 }
0045 binary_ofstream& binary_ofstream::operator<<(int n) {
0046   fwrite(&n, sizeof(n), 1, file_);
0047   return *this;
0048 }
0049 binary_ofstream& binary_ofstream::operator<<(unsigned int n) {
0050   fwrite(&n, sizeof(n), 1, file_);
0051   return *this;
0052 }
0053 binary_ofstream& binary_ofstream::operator<<(long n) {
0054   fwrite(&n, sizeof(n), 1, file_);
0055   return *this;
0056 }
0057 binary_ofstream& binary_ofstream::operator<<(unsigned long n) {
0058   fwrite(&n, sizeof(n), 1, file_);
0059   return *this;
0060 }
0061 binary_ofstream& binary_ofstream::operator<<(float n) {
0062   fwrite(&n, sizeof(n), 1, file_);
0063   return *this;
0064 }
0065 binary_ofstream& binary_ofstream::operator<<(double n) {
0066   fwrite(&n, sizeof(n), 1, file_);
0067   return *this;
0068 }
0069 
0070 binary_ofstream& binary_ofstream::operator<<(bool n) { return operator<<(static_cast<char>(n)); }
0071 
0072 binary_ofstream& binary_ofstream::operator<<(const std::string& s) {
0073   (*this)
0074       << (uint32_t)
0075              s.size();  // Use uint32 for backward compatibilty of binary files that were generated on 32-bit machines.
0076   fwrite(s.data(), 1, s.size(), file_);
0077   return *this;
0078 }