簡體   English   中英

c中如何使用chdir()將當前目錄更改為指定目錄?

[英]How to change the current directory to a designated directory using chdir() in c?

編輯

存在的目錄不一定是主目錄的子目錄。 它可以是主目錄的子目錄的子目錄。

編輯結束

我正在讀取用戶輸入(例如,cd existsDirectory)以將當前目錄更改為“existedDirectory”。 我知道

chdir(getenv("HOME"));

可以將當前目錄更改為主目錄,所以我嘗試了以下方法:

chdir(getenv("/existedDirectory"));
chdir(getenv("existedDirectory"));
chdir(getenv("~/existedDirectory"));
chdir("/existedDirectory");
chdir("existedDirectory");
chdir("~/existedDirectory");

沒有任何效果。 任何幫助將不勝感激。

chdir接受一個帶有要更改的路徑的字符串參數。 它沒有其他特殊處理(環境變量或家庭或其他任何東西),所以如果你想要這些東西,你需要構建一個字符串來傳遞給它。

chdir("/existingDirectory");

更改為根目錄中的現有目錄-它具有絕對路徑。 因此,它必須是您在運行ls /時看到的目錄之一。

chdir("exisitingDirectory");

將更改為當前主管的現有子目錄。

如果要更改到主目錄的子目錄,則需要以下內容:

char path[PATH_MAX];
sprintf(path, "%s/%s", getenv("HOME"), "subdir");
chdir(path);

C 中的chdir()只影響調用它的進程。 您的 shell 和您的程序是兩個不同的進程,它們分別運行。 因此,指示工作目錄的環境變量 $PWD 只會針對您的應用程序進行更改。 也檢查這個資源

注意: chdir()不會改變當前 shell 的工作目錄。 因為當程序在shell中執行時,shell遵循fork on exec機制。 因此,它不會影響當前的 shell。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM