如何在C++中将整数vector存储到磁盘并从保存文件读取整数?
二进制文件读写vector的问题修正
问题根源分析
你写入两个整数到二进制文件后只读到最后一个值,核心问题有三个:
- 文件打开模式错误:读取时误用了
std::fstream::out模式,这是写入模式,会破坏文件原有内容(或创建空文件),应该使用输入模式std::fstream::in(std::ifstream默认就是输入模式,可省略)。 - 循环语法错误:
while (file.read(...));末尾的分号让循环体为空,每次读取都会覆盖变量内容,循环结束后仅保留最后一次读取的结果。 - 冗余的自定义类:
ValueGet类完全没必要,直接用int变量读取更简洁。
修正后的完整代码
#include <fstream> #include <vector> #include <iostream> int main() { // 写入逻辑:这部分是正确的 int first_int = 47; int second_int = 88; std::vector<int> int_vec; int_vec.push_back(first_int); int_vec.push_back(second_int); std::ofstream outfile("int_outfile.txt", std::ofstream::binary); outfile.write(reinterpret_cast<const char*>(int_vec.data()), sizeof(int) * int_vec.size()); outfile.close(); // 修正后的读取逻辑 std::ifstream file("int_outfile.txt", std::ifstream::binary); if (!file) { std::cout << "File Not Found." << std::endl; return 1; } // 直接用int读取,简洁直观 int num; std::cout << "读取到的整数:"; while (file.read(reinterpret_cast<char*>(&num), sizeof(num))) { std::cout << num << " "; } std::cout << std::endl; file.close(); return 0; }
关键修正说明
- 模式修正:读取时仅用
std::ifstream::binary,std::ifstream默认以输入模式打开文件,无需额外指定in,更不能加out。 - 循环修正:移除while语句末尾的分号,将打印操作放入循环体内,每次读取到整数就立即输出,避免覆盖。
- 简化逻辑:删除冗余的
ValueGet类,直接使用int变量存储读取结果,减少代码复杂度。
内容的提问来源于stack exchange,提问作者Ant
相关产品推荐
相关产品推荐

