Reading and writing a std::vector into a file correctly(正确读取和写入 std::vector 到文件中)
问题描述
这就是重点.如何写入和读取其中包含 std::vector 的二进制文件?
That is the point. How to write and read binary files with std::vector inside them?
我在想:
//============ WRITING A VECTOR INTO A FILE ================
const int DIM = 6;
int array[DIM] = {1,2,3,4,5,6};
std::vector<int> myVector(array, array + DIM);
ofstream FILE(Path, ios::out | ofstream::binary);
FILE.write(reinterpret_cast<const char *>(&myVector), sizeof(vector) * 6);
//===========================================================
但我不知道如何阅读这个向量.因为我认为以下是正确的,但事实并非如此:
But I don't know how to read this vector. Because I thought that the following was correctly but it isn't:
ifstream FILE(Path, ios::in | ifstream::binary);
FILE.read(reinterpret_cast<const char *>(&myVector), sizeof(vector) * 6);
那么,如何执行操作?
推荐答案
尝试使用 ostream_iterator
/ostreambuf_iterator
, istream_iterator
/istreambuf_iterator
和 STL copy
方法:
Try using an ostream_iterator
/ostreambuf_iterator
, istream_iterator
/istreambuf_iterator
, and the STL copy
methods:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <fstream> // looks like we need this too (edit by π)
std::string path("/some/path/here");
const int DIM = 6;
int array[DIM] = {1,2,3,4,5,6};
std::vector<int> myVector(array, array + DIM);
std::vector<int> newVector;
std::ofstream FILE(path, std::ios::out | std::ofstream::binary);
std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(FILE));
std::ifstream INFILE(path, std::ios::in | std::ifstream::binary);
std::istreambuf_iterator iter(INFILE);
std::copy(iter.begin(), iter.end(), std::back_inserter(newVector));
这篇关于正确读取和写入 std::vector 到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:正确读取和写入 std::vector 到文件中
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01