User Tools

Site Tools


programming:cpp:binary

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
programming:cpp:binary [2022/04/11 07:22]
odagawa
programming:cpp:binary [2022/04/30 17:48] (current)
odagawa
Line 5: Line 5:
 ROOT を使っている限りは気にする必要がないが, emulsion とのデータをやり取りするために必要だった. ROOT を使っている限りは気にする必要がないが, emulsion とのデータをやり取りするために必要だった.
  
-えば以下のようなクラスかんる.+このき,vector のような可変長配列は要素数保持しておく必要.\\ 
 +したがって,''ReadMyClassHeader/WriteMyClassHeader'' という関数を作成し,\\ 
 +単なるメンバ変数とともに vector の要素数を追加で読み書きできるようにしておくことがポイントだと思う
  
-<code cpp> +たとえば以下のようなクラスを考える. 
-class Myclass {+ 
 +<code cpp MyClass.hpp> 
 +#ifndef MYCLASS_HPP 
 +#define MYCLASS_HPP 
 + 
 +#include <vector> 
 + 
 +class MyClass {
 public :  public : 
   int var1;   int var1;
Line 14: Line 23:
   std::vector<double> vec;   std::vector<double> vec;
 }; };
 +#endif
 </code> </code>
  
 読み取りは以下のように行う. 読み取りは以下のように行う.
  
-<code cpp>+<code cpp TestBinaryInput.cpp>
 #include <fstream> #include <fstream>
 +#include <string>
 #include <vector> #include <vector>
 #include <iomanip> #include <iomanip>
Line 60: Line 71:
 書き込みは以下のように行う. 書き込みは以下のように行う.
  
-<code cpp>+<code cpp TestBinaryOutput.cpp
 +#include <fstream> 
 +#include <string> 
 +#include <vector> 
 +#include <iomanip>
  
 +#include "MyClass.hpp"
 +
 +void WriteMyClassHeader(std::ofstream &ofs, MyClass myclass) {
 +  int vec_size = myclass.vec.size();
 +  ofs.write((char*)& myclass.var1, sizeof(int));
 +  ofs.write((char*)& myclass.var2, sizeof(double));
 +  ofs.write((char*)& vec_size, sizeof(int));
 +}
 +
 +int main() {
 +  std::string filename = "test.bin";
 +  std::ofstream ofs(filename, std::ios::binary);
 +  
 +  std::vector<MyClass> myclass_vector;
 +  // myclass vector を適当に作成
 +  
 +  if ( !ofs ) {
 +    std::cerr << "File : " << filename << " not found." << std::endl;
 +    std::exit(1);
 +  }
 +  else if ( myclass_vector.empty() ) {
 +    std::cerr << "Data null" << std::endl;
 +    std::exit(1);
 +  }
 +  else {
 +    for ( auto myclass : myclass_vector ) {
 +      WriteMyClassHeader(ofs, myclass);
 +      for ( auto ivec : myclass.vec ) {
 +        ofs.write((char*)& ivec, sizeof(double));
 +      }
 +    }
 +  }
 +  
 +  std::exit(0);
 +  
 +}
 </code> </code>
programming/cpp/binary.1649661744.txt.gz · Last modified: 2022/04/11 07:22 by odagawa