[英]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? 这段代码中
std::filesystem::copy()
和std::filesystem::copy_file()
之间有什么区别?
#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()
:“复制文件或目录” copy_file()
: "copies file contents" copy_file()
:“复制文件内容” 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.) (我正在使用g ++ 8.2.0。请记住链接libstdc ++ fs,否则你将对std :: filesystem有未定义的引用。)
Yes, barring error or cases you do not expect. 是的,除非你没有想到的错误或案例。
If src
was silently replaced with a directory, they behave differently. 如果
src
被静默替换为目录,则它们的行为会有所不同。 If dst
exists and is a directory, I believe they'll behave differently. 如果
dst
存在并且是一个目录,我相信它们的行为会有所不同。 Some copy options may apply to copy and not to copy_file as well. 某些复制选项可能适用于复制,也不适用于copy_file。
But when copying from one file to another file or to a name whose file does not exist, copy
invokes copy_file
. 但是,当从一个文件复制到另一个文件或文件不存在的名称时,
copy
调用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
. 请注意,有人可以删除
foo.txt
并将其替换为上次检查(比如前一行)和copy
或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
. 为此,如果您打算复制一个文件,请使用
copy_file
。 (And always check errors.) (并始终检查错误。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.