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

前端 未结 2 1911

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:31

    There are a number of flaws in your code:

    1. you define a variable named FILE THIS IS BAD BAD BAD. FILE is a name of an already existing object, it's comparable to naming an instance of a vector as: std::vectorarray{}.
      Not only is it confusing it's extremely dangerous as it will almost certainty lead to naming clashes. Plus, all capitol names should be reserved for macros.

    2. you never check if the file is actually opened, if it isn't the compiler will not warn you and the stream will not give any indication of failure (unless explicitly checked). So, you should always check. The simplest way is too use the streams boolean operator:
      if (!ifile) throw std::runtime_error("error opening file");

    3. you wrote that this doesn't compile:

      std::copy(iter.begin(),iter.end(),std::back_inserter(newVector));

      Why would this work? Iterators themselves don't have begin and end functions, the objects associated with the iterator have those methods.

    4. Piecing all that together here is a modified version of your code:

      {
          std::string path("numbersfile");
      
          std::vector myVector{ 1,16,32,64 };
          std::vector newVector{};
      
      
          std::ofstream outfile(path, std::ios_base::binary);
          std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator(outfile));
      
          outfile.close(); 
      
          std::ifstream infile(path,std::ios_base::binary);
          std::istreambuf_iterator iter(infile);
          std::copy(iter, std::istreambuf_iterator(),    std::back_inserter(newVector)); // this leaves newVector empty
      
          infile.close(); // close explicilty for consistency 
      }
      

提交回复
热议问题