我使用下面的代码将文件、目录、软链接、硬链接从一个目录复制到另一个目录。
#include <fstream>
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
//function copy files
void cpFile(const fs::path & srcPath,
const fs::path & dstPath) {
std::ifstream srcFile(srcPath, std::ios::binary);
std::ofstream dstFile(dstPath, std::ios::binary);
if (!srcFile || !dstFile) {
std::cout << "Failed to get the file." << std::endl;
return;
}
dstFile << srcFile.rdbuf();
srcFile.close();
dstFile.close();
}
//function create new directory
void cpDirectory(const fs::path & srcPath,
const fs::path & dstPath) {
fs::create_directories(dstPath);
for (const auto & entry: fs::directory_iterator(srcPath)) {
const fs::path & srcFilePath = entry.path();
const fs::path & dstFilePath = dstPath / srcFilePath.filename();
//if directory then create new folder
if (fs::is_directory(srcFilePath)) {
cpDirectory(srcFilePath, dstFilePath);
} else {
cpFile(srcFilePath, dstFilePath);
}
}
}
int main(int argc, char *argv[]) {
const auto root = fs::current_path();
const fs::path srcPath = argv[1];
const fs::path dstPath = argv[2];
// Copy only those files which contain "Sub" in their stem.
cpDirectory(srcPath, dstPath);
return 0;
}
以下是src目录的内容:
$ ls -ltr a/
total 4
-rw-rw-r-- 1 ubuntu ubuntu 0 Sep 30 19:58 test.txt
-rw-rw-r-- 1 ubuntu ubuntu 0 Oct 1 18:12 d.txt
lrwxrwxrwx 1 root root 5 Oct 1 18:12 linkd -> d.txt
drwxrwxr-x 2 ubuntu ubuntu 4096 Oct 1 18:21 testd
当我运行代码时:
$
./copyRec a/ e/
以下是dst目录的内容:
$ls -ltr e/
total 4
drwxrwxr-x 2 ubuntu ubuntu 4096 Oct 1 18:21 testd
-rw-rw-r-- 1 ubuntu ubuntu 0 Oct 1 18:38 test.txt
-rw-rw-r-- 1 ubuntu ubuntu 0 Oct 1 18:38 linkd
-rw-rw-r-- 1 ubuntu ubuntu 0 Oct 1 18:38 d.txt
其中 linkd 是到 d.txt 的软链接,但它不被保留并显示为常规文件。 请帮忙。
您必须采取特定操作才能保留符号链接。文件系统库不会为你做这件事。
if (fs::is_directory(srcFilePath)) {
您已经知道如何使用
is_directory
。如果您返回并查看您了解 is_directory
的 C++ 参考资料或教科书,您还会发现 is_symlink
的描述,它检查给定条目是否是符号链接。
read_symlink
读取符号链接,并使用 create_symlink
重新创建它。