Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 680
Stéphane Avatar asked Aug 20 '18 00:08

Stéphane


People also ask

What is the name of the library that must be imported to manage the filesystem?

The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories.


Video Answer


2 Answers

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

like image 101
Yakk - Adam Nevraumont Avatar answered Nov 15 '22 00:11

Yakk - Adam Nevraumont


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.

like image 42
1201ProgramAlarm Avatar answered Nov 14 '22 22:11

1201ProgramAlarm