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

后端 未结 5 1224
梦毁少年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 
    #include 
    #include 
    #include 
    
    #include  // 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 myVector(array, array + DIM);
    std::vector newVector;
    
    std::ofstream FILE(path, std::ios::out | std::ofstream::binary);
    std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator(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));
    

提交回复
热议问题