Reading and writing a std::vector into a file correctly

后端 未结 5 1151
梦毁少年i
梦毁少年i 2020-12-01 04:26

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

I was thinking something like:

//============ WRITING A VECTOR IN         


        
相关标签:
5条回答
  • 2020-12-01 05:01

    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));
    
    0 讨论(0)
  • 2020-12-01 05:11

    You can use

    #include <boost/serialization/vector.hpp>
    

    to serialize your vector. Read a tutorial here: http://www.boost.org/libs/serialization/doc/tutorial.html#stl `

    0 讨论(0)
  • 2020-12-01 05:12

    Use boost::serialization.

    If you don't want use boost - write size and vector.

    size_t sz = myVector.size();
    FILE.write(reinterpret_cast<const char*>(&sz), sizeof(sz));
    FILE.write(reinterpret_cast<const char*>(&myVector[0]), sz * sizeof(myVector[0]));
    
    0 讨论(0)
  • 2020-12-01 05:23

    Before reading vector, you should resize it: yourVector.size(numberOfElementsYouRead).

    Besides, sizeof(vector<your_type>) is just the size of the vector object internal implementation; vector element size is sizeof(std::vector<your_type>::value_type).

    Then read it like this:

    file.read(reinterpret_cast<char *>(&myVector[0]), sizeof(vector<int>::element_type) * element_count); 
    
    0 讨论(0)
  • 2020-12-01 05:26

    I used the fact that the data() method returns an address you can use for reading AND for writing.

    // Assume outf is a writable filepointer (binary). // write myVector.size() to file, then

    fwrite(myVector.data(), sizeof(decltype(myVector)::value_type), myVector.size(), outf);
    

    to read:

    // read MyVector.size() from file as nv, inpf is read filepointer

    MyVector.resize(nv);
    fread(MyVector.data(), sizeof(decltype(MyVector)::value_type), nv, inpf);
    

    clinging to old ways in file io, but please ignore that (even if it might irritate you :)).

    A weakness is that endianness is unsupported in this way.

    0 讨论(0)
提交回复
热议问题