I am using std::copy
to copy the objects in std::deque
to a file. The code is working fine but I need to check if copying was successful and accordingly I need to set the flag or else throw exception.
I have googled but could not find the solution how to check if std::copy
has successfully copied the values into the file.
Could someone please throw a light on it.
Return value: iterator – it is an iterator to the end of the target range where elements have been copied.
The reason why main use 0 for success is that it is used as the exit code of the application to the operating system, where 0 typically means success and 1 (or higher) means failure.
return 0: A return 0 means that the program will execute successfully and did what it was intended to do. return 1: A return 1 means that there is some error while executing the program, and it is not performing what it was intended to do.
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
If writing to the file fails, then the file stream's error flags will be set - you can either check these after the copy, or call the exceptions
member function first to make it throw an exception on error. If anything else fails, then an exception will be thrown.
AFAIK std::copy algorithm doesn't check anything and just iterates over all elements and copies them to output iterator. This means that you should provide enought space in output iterator yourself otherwise the behaviour is unspecified.
So in your case you should yourself check that the output file is writable, etc..
One of possible ways to check this I think use error flags for the file stream you're using, i.e. after copying check that your ofstream
is good
(you can use good()
, eof()
, fail()
and bad()
functions for this).
The second approach is to check the return value of std::copy
. As it returns an iterator to the end of the destination range (which points to the element following the copy of last) then you can calculate the difference between the return value of std::copy
and your output iterator and make sure that its equal to the size of your deque
. E.g. (pseudocode)
OutputIterator result = std::copy(input.begin(), input.end(), output);
assert(result - output == input.end() - input.begin());
EDIT: The second approach works only when output
is also input iterator type, so std::distance
to work for it. It will be more correct to write:
assert(std::distance(output, result) == std::distance(input.begin(), input.end()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With