std::filesystem::path source_path =
"source.txt"
;
std::filesystem::path destination_path =
"destination.txt"
;
std::filesystem::path destination_folder =
"C:\\MyFolder"
;
std::filesystem::
copy
(source_path, destination_folder / destination_path);
return
0
;
首先,我们需要包含
iostream
、
fstream
和
filesystem
头文件,因为我们将使用这些库来进行文件操作。然后,我们定义源文件的路径
source_path
、目标文件的路径
destination_path
和目标文件夹的路径
destination_folder
。
接着,我们使用
std::filesystem::copy
函数将源文件复制到目标文件夹中的指定位置。这个函数会将源文件复制到目标文件夹中,并以
destination_path
作为复制后的文件名。
请注意,如果目标文件夹不存在,
std::filesystem::copy
函数将抛出一个异常。你需要使用
std::filesystem::create_directory
函数来创建目标文件夹,如下所示:
if (!std::filesystem::exists(destination_folder))
std::filesystem::create_directory(destination_folder);
这个函数会检查目标文件夹是否存在,如果不存在,则会创建它。
希望这个示例能够帮助你复制文件到指定目录。如果你有任何问题,请随时提问。