What is the difference between std::filesystem::copy() and std::filesystem::copy_file()?
Asked Answered
S

2

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.)

Sideswipe answered 20/8, 2018 at 0:51 Comment(0)
J
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.)

Jab answered 20/8, 2018 at 1:3 Comment(0)
R
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.

Reiche answered 20/8, 2018 at 1:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.