我有一个向量,其大小可能非常大(100 万个元素)。我将向量的内容作为字节值写入文件。我无法弄清楚如何将字节值读回向量中。
这是代码:
#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
// Filling a vector with values
std::vector<bool> 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 < ve.size(); i++)
cout << ve.at(i) << ".";
cout << 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*)&(ve[0]), ve.size());
outfile.close();
// Reading the file and filling the vector with values
ifstream infile ("abc.txt", ifstream::binary);
vector<bool> out_ve((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
while( !infile.eof() )
out_ve.push_back(infile.get());
// Checking if the values read are the same as the original values
cout << "SIZE: " << out_ve.size() << endl;
for(unsigned int i = 0; i < out_ve.size(); i++)
cout << out_ve.at(i) << ".";
cout << endl;
infile.close();
return 0;
}
[编辑] 写入后关闭文件,输出与输入有很大不同。
1.0.1.0.1.
SIZE: 6
1.1.1.0.1.1.
如何将正确的元素放入向量 out_ve?