#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <numeric> class MyClass { private: class BitField { public: unsigned int a_: 10; unsigned int b_: 8; unsigned int c_: 12; unsigned int d_: 2; BitField() : a_(0), b_(0), c_(0), d_(0){} BitField(int a,int b, int c, int d) : a_(a), b_(b), c_(c), d_(d){}; std::string to_string() const { std::stringstream ss; ss << a_ << "," << b_ << "," << c_ << "," << d_; return ss.str(); } } bf_; std::string str_; public: MyClass() : str_(""){}; MyClass(int a,int b, int c, int d, const std::string &str) : bf_(a,b,c,d), str_(str){}; std::string to_string() const { std::stringstream ss; ss << bf_.to_string() << "," << str_; return ss.str(); } uint32_t get_dumpsize() const { uint32_t sum = 0; sum += sizeof(bf_); sum += str_.length(); return sum; } friend std::ostream &operator<<(std::ostream &os, const MyClass &my); }; // std::copyを使用するにはoperator<<をオーバロードする std::ostream &operator<<(std::ostream &os, const MyClass &my){ os.put(my.bf_.a_); os.put(my.bf_.b_); os.put(my.bf_.c_); os.put(my.bf_.d_); os.write(my.str_.c_str(), my.str_.length()); return os; } int main(int argc, const char * argv[]) { std::vector<MyClass> my_class_vector; for(int i = 0; i < 10; i++){ my_class_vector.emplace_back(i + 1, i * 100, i * 1000, i + 3, "end!"); } std::ofstream ofs("/Users/usadamasa/Desktop/binaryfile.bin", std::ios::binary); if(!ofs.is_open()){ std::cerr << "File Open Error" << std::endl; return 1; } // stringがメンバ変数にあるため書き込みサイズとクラスの確保しているサイズは異なる std::cout << "sizeof MyClass :" << sizeof(MyClass) << std::endl; std::cout << "write size :" << my_class_vector.at(0).get_dumpsize() << std::endl; for(const auto &v : my_class_vector){ std::cout << v.to_string() << std::endl; } std::copy(my_class_vector.begin(), my_class_vector.end(), std::ostream_iterator<MyClass>(ofs)); }
ファイル出力結果(2進数)
| a | b | c | d| str | +--------+--------+---------------+--+-----------------------------------+ |00000001|00000000|00000000 000000|11|01100101 01101110 01100100 00100001| |00000010|01100100|11101000 000000|00|01100101 01101110 01100100 00100001| |00000011|11001000|11010000 000000|01|01100101 01101110 01100100 00100001| |00000100|00101100|10111000 000000|10|01100101 01101110 01100100 00100001| |00000101|10010000|10100000 000000|11|01100101 01101110 01100100 00100001| |00000110|11110100|10001000 000000|00|01100101 01101110 01100100 00100001| |00000111|01011000|01110000 000000|01|01100101 01101110 01100100 00100001| |00001000|10111100|01011000 000000|10|01100101 01101110 01100100 00100001| |00001001|00100000|01000000 000000|11|01100101 01101110 01100100 00100001| |00001010|10000100|00101000 000000|00|01100101 01101110 01100100 00100001|