Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

c++ - Reading and writing a std::vector into a file correctly

That is the point. How to write and read binary files with std::vector inside them?

I was thinking something like:

//============ 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);

So, how to perform the operation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...