Boost logo

Boost :

Subject: [boost] [filesystem] copy_file() not atomic proposed fix
From: Beman Dawes (bdawes_at_[hidden])
Date: 2009-05-12 08:41:05

Ticket #2925 complains that "boost::filesystem cannot atomically copy
file if target exists", and gives this example:

    void copy (std::string src,
               std::string target,
               int flags)
      if ( (flags & Overwrite) &&
           boost::fs::exists (tgt) )
        boost::fs::remove (tgt);

      // second process can create file again here

      boost::fs::copy_file (src, tgt);

Changing boost::filesystem::copy_file() to overwrite isn't viable; (1)
that just creates a mirror of the race condition when an overwrite is
actually desired to be an error, and (2) changing the behavior would
silently break existing code.

The proposed solution is to add an option to copy_file():

    enum class copy_option { fail_if_exists, overwrite_if_exists };

    void copy_file( const Path & from_path, const Path & to_path,
      copy_option option=copy_option::fail_if_exists );

The implementation would be atomic on both POSIX and Windows.



Boost list run by bdawes at, gregod at, cpdaniel at, john at