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

前端 未结 2 1917

I\'m trying to understand the answer provided here, but I can\'t seem to make it work.

Here is what I\'ve tried:

#include 
#include          


        
2条回答
  •  我在风中等你
    2020-12-04 00:20

    The file is not ready to be read by the time the second copy is called. (Thanks to Piotr Skotnicki for his answer in the comments)

    A call to flush allows the program to work:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string path("numbersfile");
    
        std::vector myVector{1,16,32,64};
        std::vector newVector{};
    
        std::ofstream FILE(path,std::ios::out | std::ofstream::binary);
        std::copy(myVector.begin(),myVector.end(),std::ostreambuf_iterator(FILE));
        FILE.flush(); // required here
    
        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)); //this doesn't compile
        std::copy(iter,std::istreambuf_iterator{},std::back_inserter(newVector)); // this leaves newVector empty
        return 0;
    }
    

    The ofstream is still in scope when the ifstream is created. Had the ofstream's destructor been called then the file would also have been ready for the ifstream. In the following program the ifstream is automatically destructed:

    #include 
    #include 
    #include 
    #include 
    
    std::string filename("numbersfile");
    
    std::vector myVector{1.342, 16.33, 32.1, 12364};
    
    void write_vector_to_file(const std::vector& myVector, std::string filename);
    std::vector read_vector_from_file(std::string filename);
    
    int main()
    {
        write_vector_to_file(myVector, filename);
        auto newVector{read_vector_from_file(filename)};
        return 0;
    }
    
    void write_vector_to_file(const std::vector& myVector, std::string filename)
    {
        std::ofstream ofs(filename, std::ios::out | std::ofstream::binary);
        std::ostream_iterator osi{ofs," "};
        std::copy(myVector.begin(), myVector.end(), osi);
    }
    
    std::vector read_vector_from_file(std::string filename)
    {
        std::vector newVector{};
        std::ifstream ifs(filename, std::ios::in | std::ifstream::binary);
        std::istream_iterator iter{ifs};
        std::istream_iterator end{};
        std::copy(iter, end, std::back_inserter(newVector));
        return newVector;
    }
    

提交回复
热议问题