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
There are a number of flaws in your code:
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::vector
.
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.
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");
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.
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
}