title: Reading and writing vector<bool> to a file in c++
body: <p>I am having a vector whose size can be really big (1 million elements). I am wrote the contents of the vector to a file as byte values. I am not able to figure out how I can read the byte values back into the vector.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#include &lt;fstream&gt;
  #include &lt;vector&gt;
  #include &lt;iterator&gt;
  #include &lt;iostream&gt;
  using namespace std;
  
  int main()
  {
    // Filling a vector with values
    std::vector&lt;bool&gt; ve;
    ve.push_back(true);
    ve.push_back(false);
    ve.push_back(true);
    ve.push_back(false);
    ve.push_back(true);
    // Printing the values of the vector
    for(unsigned int i = 0; i &lt; ve.size(); i++)
        cout &lt;&lt; ve.at(i) &lt;&lt; ".";
    cout &lt;&lt; endl;
  
    // Writing the vector contents to a file
    const char* file_name = "abc.txt";
    ofstream outfile(file_name, ios::out | ios::binary);
    outfile.write((const char*)&amp;(ve[0]), ve.size());
    outfile.close();
    // Reading the file and filling the vector with values
    ifstream infile ("abc.txt", ifstream::binary);
    vector&lt;bool&gt; out_ve((std::istreambuf_iterator&lt;char&gt;(infile)),
                         std::istreambuf_iterator&lt;char&gt;());
  
    while( !infile.eof() )
        out_ve.push_back(infile.get());
  
    // Checking if the values read are the same as the original values
    cout &lt;&lt; "SIZE: " &lt;&lt; out_ve.size() &lt;&lt; endl;
    for(unsigned int i = 0; i &lt; out_ve.size(); i++)
      cout &lt;&lt; out_ve.at(i) &lt;&lt; ".";
    cout &lt;&lt; endl;
  
    infile.close();
    return 0;
  }
  </code></pre>
  
  <p>[edit] Closed the file after writing and the output is very different from the input.</p>
  
  <pre><code>1.0.1.0.1.
  SIZE: 6
  1.1.1.0.1.1.
  </code></pre>
  
  <p>How can I get the correct elements into the vector out_ve?</p>