【问题标题】:Copy directory with symbolic links pointing to the copied files (inside directory tree)使用指向复制文件的符号链接复制目录(在目录树内)
【发布时间】:2012-03-28 17:27:02
【问题描述】:

我想复制一个文件夹及其所有内容,包括子文件夹。我在 Ubuntu 上使用 C。

到目前为止,复制常规文件和文件夹很容易并且完成,但是复制链接的规范(现在是符号)是它们应该链接到复制的文件。现在我只对目录树中的链接感兴趣。

(虽然我认为树外的链接应该更容易 - 只需将完整路径复制到新链接并找出它们是否属于树 - 尽管sarnold 给了我关于使用 @987654322 的提示,但这很难@ 来实现)

所以我有一个 readlink 返回的绝对路径:

/home/giorgos/Desktop/folder/folder1/a.pdf

最坏的情况是:

/home/giorgos/Desktop/folder/folder/folder/folder1/a.pdf

但我找不到检索目录树的相对路径的方法。如果我能找到它,我可以用复制的目录名称替换它:

 /home/giorgos/Desktop/March/folder/myfolder/folder/folder1/a.pdf

我不能使用 cp 或 system() 函数或那种类型的函数,解决方案必须是低级别的。我可以使用 c 库和 GNU,但如果我有兴趣,请发布答案。

【问题讨论】:

  • 使用 tar 和 untar -h 会有所帮助。这将放置链接的目标而不是链接名称。
  • 我对链接的目标不感兴趣我已经复制了那个,我想在新目录树中有一个同名的链接,指向新目录中的相应文件(复制)树

标签: c linux directory copy symlink


【解决方案1】:

假设您需要将目录SRC_DIR 复制到DST_DIR,这两个都是绝对路径(如果没有,使用getcwd 转换它们很简单)。

这个伪代码应该涵盖所有可能性(它可能涉及大量重复使用strtok 来标记'/'分隔符处的路径):

if (SRC_DIR/SUBDIRS/LINK is a symlink that points to TARGET_LOCATION)
  {
    // TARGET_LOCATION may be relative *or* absolute. Make it absolute:
    if (TARGET_LOCATION does not begin with '/')
      {
        prepend SRC_DIR/ to it
      }
    if (TARGET_LOCATION contains a subdirectory named '..')
      {
        replace occurances of 'SOMEDIRNAME/..' with ''
      }
    if (TARGET_LOCATION contains a subdirectory named '.')
      {
        replace occurances of '/.' with ''
      }
    // now TARGET_LOCATION is an absolute path

    if (TARGET_LOCATION does not begin with SRC_DIR)
      {
        // symlink points outside tree
        create symlink DST_DIR/SUBDIRS/LINK pointing to TARGET_LOCATION
      }
    else
      {
        // symlink points inside tree
        strip SRC_DIR from beginning of TARGET_LOCATION
        prepend DST_DIR to TARGET_LOCATION
        create symlink DST_DIR/SUBDIRS/LINK pointing to TARGET_LOCATION
      }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2020-11-10
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2013-07-28
    相关资源
    最近更新 更多