ofstream::write 为部分文件写入零

ofstream::write writes zeros for part of the file

我想将 vector 的内容写入二进制文件。当前程序应该在文件中保存整数 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

如何将整个向量写入文件?

正如 user253751 和 Marek R 指出的那样,问题是我没有以二进制模式阅读。

之前:

std::ifstream file("file.bin");

更正:

std::ifstream file("file.bin", std::ios::binary);