c++ - 使用 C++ 将文件和目录从一个目录递归复制到另一个目录时,不会保留软链接(soft link)

标签 c++ linux filesystems disk dirent.h

我使用下面的代码将文件、目录、软链接(soft link)、硬链接(hard link)从一个目录复制到另一个目录。

#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 的软链接(soft link),但它不被保留并显示为常规文件。 请帮忙。

最佳答案

您必须采取特定操作才能保留符号链接(symbolic link)。文件系统库不会为你做这件事。

   if (fs::is_directory(srcFilePath)) {

您已经知道如何使用 is_directory。如果您返回并查看您了解 is_directory 的 C++ 引用资料或教科书,您还会发现 is_symlink 的描述。它检查给定的条目是否是符号链接(symbolic link)。

然后,您将需要使用read_symlink读取符号链接(symbolic link),以及 create_symlink重新创建它。

关于c++ - 使用 C++ 将文件和目录从一个目录递归复制到另一个目录时,不会保留软链接(soft link),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77211829/

相关文章:

ios - 我的应用占用了 iPad 存储上的虚拟空间

c++ - QT 5 [ 错误 : QtGui/QApplication: No such file or directory]

C++如何调用父类的友元函数?

linux - 在 --gc-sections 之后更新链接器变量

python - 禁止在 Python 中访问 exec 和 eval 中的文件系统

c++ - boost::filesystem 相对路径和当前目录?

c++ - 查询 D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY 的 WMI

c++ - 无法调用函数引用 c++

linux - 为什么写系统调用在 linux x86_64 (nasm) 上最后打印 `%`?

Linux -> 终端命令 -> Grep -> 与符号相关的表达式/异常