title: Write a vector of cv::Mat to binary file in c++
body: <p>As in the title, I have <code>std::vector&lt;cv::Mat&gt; matrices</code> which I want to write/read to/from binary file.</p>
  
  <p>Now, following <a href="https://stackoverflow.com/a/14089675/4480180">this</a> answer, all I should do is for writing is:</p>
  
  <pre><code> ofstream fout("matrices.bin", ios::out | ios::binary);
   size_t size = matrices.size();
   fout.write((char*)&amp;size, sizeof(size));
   fout.write((char*)&amp;matrices[0], v.size() * sizeof(cv::Mat));
   fout.close();
  </code></pre>
  
  <p>However, following <a href="https://stackoverflow.com/a/32357875/4480180">this</a> answer, writing <code>cv::Mat</code> objects seems a little bit tricky, and in the answer <code>matRead</code> and <code>matWrite</code> do the job. So I wonder if instead of the code above I should do something like:</p>
  
  <pre><code>ofstream fout("matrices.bin", ios::out | ios::binary);
  size_t size = matrices.size();
  fout.write((char*)&amp;size, sizeof(size));
  for(size_t i = 0 ; i &lt; matrices.size() ; i++)
    matWrite("matrices.bin", matrices[i]);
  </code></pre>
  
  <p>However this code doesn't work since <code>matWrite()</code> overwrites <code>matrices.bin</code> at each cycle, so I should append the size of <code>matrices[i]</code> as offset before writing the matrix itself.</p>
  
  <p>What should I do?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I came up with this solution, rewriting <code>matWrite</code> and <code>matRead</code> with optional arguments for appending matrices during writing and starting to read from a certain point:</p>
  
  <pre><code>void matwrite(const std::string&amp; filename, const cv::Mat&amp; mat, const bool append = false) {
  
      std::ofstream fs;
      if(append)
          fs.open(filename.c_str(), std::fstream::binary | std::fstream::app);
      else
          fs.open(filename.c_str(), std::fstream::binary);
  
  //the rest of matwrite is the same...
  
  }
  
  cv::Mat matRead(const std::string&amp; filename, size_t &amp;offset = 0)
  {
      std::ifstream fs(filename, std::fstream::binary);
      fs.seekg(offset);
      ...
      offset += 4 * sizeof(int) + CV_ELEM_SIZE(type) * rows * cols; //update offset //move offset of 4 ints and mat size
      return mat;
  }
  </code></pre>
  
  <p>And functions are called with:</p>
  
  <pre><code>//writing:
  for(size_t i = 0 ; i&lt;v.size() ; i++)
    writemat(filename, v[i], true);
  //reading:
  size_t offset = 0;
  for(size_t i = 0 ; i&lt;size ; i++){ // size = v.size() during writing
    cv::Mat mat = matRead(filename, offset);
    v.push_back(mat);
  }
  </code></pre>