how to perform boost::filesystem copy_file with overwrite

Solution 1:

There's a third enum argument to copy_file, boost::filesystem::copy_option::overwrite_if_exists

copy_file(source_path, destination_path, copy_option::overwrite_if_exists);

https://www.boost.org/doc/libs/1_75_0/libs/filesystem/doc/reference.html

Solution 2:

Beware of boost::copy_file with copy_option::overwrite_if_exists! If the destination file exists and it is smaller than the source, the function will only overwrite the first size(from_file) bytes in the target file.

At least for me this was a caveat since I presumed copy_option::overwrite_if_exists affects files and not content

Solution 3:

Test if the destination file exists first and if it does then remove it :

if (exists (to_fp))
    remove (to_fp);
copy_file (from_fp, to_fp);

Or if you're worried about the file appearing between the test and the copy then you could write to a temporary file and then rename it to the destination file.