How to return std :: copy value in case of success or failure?

I use std::copy to copy objects in std::deque to a file. The code works fine, but I need to check if the copy was successful, and accordingly I need to set a flag or throw an exception.

I have googled but could not find a solution on how to check if std::copy copied the values ​​to the file successfully.

Maybe someone will try to shed light on him.

+6
source share
2 answers

If the write to the file failed, the error flags of the file stream will be set - you can either check them after copying, or first call the exceptions member function to force an exception to be thrown when an error occurs. If something else does not work, an exception will be thrown.

+5
source

AFAIK std :: copy the algorithm does not check anything and simply iterates over all elements and copies them to display the iterator. This means that you must provide enough space in the output iterator yourself, otherwise the behavior is not specified.

So, in your case, you must make sure that the output file is writable, etc. One of the possible ways to check this, I think, is to use error flags for the used file stream, that is, after copying, check that your ofstream is good (you can use good() , eof() , fail() and bad() for this )

The second approach is to check the return value of std::copy . Since it returns the iterator to the end of the destination range (which points to the element following the last copy), you can calculate the difference between the return value of std::copy and your output iterator and make sure that it is equal to the size of your deque . For instance. (Pseudocode)

 OutputIterator result = std::copy(input.begin(), input.end(), output); assert(result - output == input.end() - input.begin()); 

EDIT: The second approach only works when output also introduces an iterator type, so std::distance works for it. It would be more correct to write:

 assert(std::distance(output, result) == std::distance(input.begin(), input.end())); 
+2
source

Source: https://habr.com/ru/post/910578/


All Articles