6

What is the difference between std::filesystem::copy() and std::filesystem::copy_file() in this code?

#include <filesystem>

void testing()
{
    const std::filesystem::path src = "foo.txt";
    const std::filesystem::path dst = "bar.txt";

    std::filesystem::copy(     src, dst, std::filesystem::copy_options::overwrite_existing);
    std::filesystem::copy_file(src, dst, std::filesystem::copy_options::overwrite_existing);
}

Docs say:

  • copy(): "copies files or directories"
  • copy_file(): "copies file contents"

Since I'm copying a single file and not directories in this example, are these two calls the same?

(I'm using g++ 8.2.0. Remember to link against libstdc++fs otherwise you'll have undefined references to std::filesystem.)

Stéphane
  • 19,459
  • 24
  • 95
  • 136

2 Answers2

8

Yes, barring error or cases you do not expect.

If src was silently replaced with a directory, they behave differently. If dst exists and is a directory, I believe they'll behave differently. Some copy options may apply to copy and not to copy_file as well.

But when copying from one file to another file or to a name whose file does not exist, copy invokes copy_file.

Note, how ever, that someone could delete foo.txt and replace it with a directory in between the last time you checked (say the previous line) and the call to copy or copy_file. When implementing robust file system interaction, you should not assume the filesystem is in a specific state, and ensure your code is written defensively. To that end, if you intend to copy one file, use copy_file. (And always check errors.)

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
4

With the copy_options you're using, and the source file being a file (and not a directory), copy will call copy_file. This isn't the case if you're dealing with directories, symbolic links, or hard links.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56