2012-03-12 33 views
2

我想複製文件夾及其所有內容,包括子文件夾。我在Ubuntu上使用C語言。複製帶有指向複製文件的符號鏈接的目錄(內部目錄樹)

複製常規文件和文件夾到目前爲止很簡單,但複製鏈接的規範(現在是符號)是它們應鏈接到複製的文件。現在我只對目錄樹內的鏈接感興趣。

(儘管我認爲樹外的鏈接應該更容易 - 只需將完整路徑複製到新鏈接,並查明它們是否屬於樹中,但這很難,儘管sarnold給了我一個關於使用rsync來實現的提示那)

所以我絕對路徑通過的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或系統()函數或諸如此類的功能,該解決方案必須是低的水平。我可以使用C庫和GNU,但是無論如何,我都有興趣發佈一個答案。

+0

..這將放置鏈接的目標而不是鏈接名稱。 – Jayan 2012-03-12 10:03:38

+0

我對鏈接的目標不感興趣我已經複製了該鏈接,我想要在新目錄樹中具有相同名稱的鏈接,指向新目錄樹中的相應文件(複製) – 2012-03-12 10:09:07

回答

0

讓我們假設您需要將目錄SRC_DIR複製到DST_DIR,這兩者都是絕對路徑(如果不是,則使用getcwd轉換它們是微不足道的)。

這個僞應該包括所有的可能性(它可能涉及到很多重複使用的strtok在「/」分隔符來標記路徑):使用焦油和解壓-h會有幫助部分

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 
     } 
    }