Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 13:31:22

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