ofstream::write 为文件的一部分写入零
我想写一个向量<的内容整数>到一个二进制文件。当前的程序应该在文件中保存 0 到 99 的整数,但它只保存前 26 个整数。
std::vector<int> vector;
for (int i = 0; i < 100; i++) vector.push_back(i);
std::ofstream outfile("file.bin", std::ios::binary);
outfile.write(reinterpret_cast<const char *>(&vector[0]), sizeof(int)*vector.size());
outfile.close();
std::ifstream file("file.bin");
file.seekg(0, std::ios_base::end);
std::size_t size = file.tellg();
file.seekg(0, std::ios_base::beg);
std::vector<int> vectorRead(size / sizeof(int));
file.read((char*)&vectorRead[0], size);
file.close();
for (int i = 0; i < vector.size(); i++) {
if (vector.at(i) != vectorRead.at(i)) std::cout << vector.at(i) << ", " << vectorRead.at(i) << std::endl;
}
代码的输出是:
26, 0
27, 0
...
99, 0
如何将整个向量写入文件?
I would like to write the contents of a vector< int> to a binary file. This current program is supposed to save the integers 0 to 99 in the file, but it only saves the first 26 integers.
std::vector<int> vector;
for (int i = 0; i < 100; i++) vector.push_back(i);
std::ofstream outfile("file.bin", std::ios::binary);
outfile.write(reinterpret_cast<const char *>(&vector[0]), sizeof(int)*vector.size());
outfile.close();
std::ifstream file("file.bin");
file.seekg(0, std::ios_base::end);
std::size_t size = file.tellg();
file.seekg(0, std::ios_base::beg);
std::vector<int> vectorRead(size / sizeof(int));
file.read((char*)&vectorRead[0], size);
file.close();
for (int i = 0; i < vector.size(); i++) {
if (vector.at(i) != vectorRead.at(i)) std::cout << vector.at(i) << ", " << vectorRead.at(i) << std::endl;
}
The output of the code is:
26, 0
27, 0
...
99, 0
How can I write the whole vector to a file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 user253751 和 Marek R 指出的那样,问题是我没有以二进制模式阅读。
之前:
更正:
As user253751 and Marek R pointed out, the issue was I was not reading in binary mode.
Before:
Corrected: