程序的工作目錄

2021-05-02 05:44:29 字數 2394 閱讀 8387

1.程序的工作目錄

#include

int chdir(char * pathname);

//chdir.c

#include

#include

#include

#include

#include

int main(void)

printf("change dir successfully/n"); /* 輸出提示資訊 */

if((fd = open("test.txt", o_creat | o_rdwr)) == -1)

if(write(fd, p, strlen(p)) == -1)

close(fd); /* 關閉檔案 */

return 0;

}2.得到程序的當前工作目錄

#include

定義函式 char * getcwd(char * buf,size_t size);

函式說明 getcwd()會將當前的工作目錄絕對路徑複製到引數buf所指的記憶體空間,引數size為buf的空間大小。在呼叫此函式時,buf所指的記憶體空間要 足夠大,若工作目錄絕對路徑的字串長度超過引數size大小,則回值null,errno的值則為erange。倘若引數buf null,getcwd()會依引數size的大小自動配置記憶體(使用malloc()),如果引數size也為0,則getcwd()會依工作目錄絕對 路徑的字串程度來決定所配置的記憶體大小,程序可以在使用完此字串後利用free()來釋放此空間 。

返回值 執行成功則將結果複製到引數buf所指的記憶體空間,或是返回自動配置的字串指標。失敗返回null,錯誤**存於errno。

//get_pwd.c

#include

#include

#include

#define max 1024

int main(void)

if(getcwd(buf, max) == null)

printf("the parent : %s/n", buf); /* 列印修改後的工作目錄 */

pid = fork(); /* 建立乙個子程序 */

if(pid == -1)else if(pid == 0)

printf("the child : %s/n", buf);

}else

}return 0;

}3.子程序工作目錄對父程序的影響

子程序修改工作目錄不會影響到父程序。此時在考慮shell程式的實現,shell呼叫fork函式和exec函式執行乙個命令,。如果cd命令以乙個程式的方式實現,然後在shell中呼叫。這相當於生成乙個子程序,然後子程序改變了目錄,但是對父程序即原shell的目錄沒影響。因此,cd命令是在shell直接實現的。

範例:#include

#include

#include

#define max 1024

int main(void)

printf("the parent』s pwd is : %s/n", buf);

pid = fork(); /* 建立乙個子程序 */

if(pid == -1)else if(pid == 0)

if(getcwd(buf, max) == null)

printf("the child』s pwd is : %s/n", buf); /* 列印子程序修改後的工作目錄 */

}else

if(getcwd(buf, max) == null)

printf("the parent』s pwd is : %s/n", buf); /* 輸出提示資訊 */

}return 0;

}由上例可以看出子程序改變工作目錄對父程序沒影響。

下面是錯誤的改變工作目錄的方法:

#include

#include

#include

#define max 1024

int main()

char buf[max];

if(getcwd(buf,max)==null){

perror("fial to get pwd");

exit(1);

printf("%s/n",buf);

if(system("cd /usr/bin")==-1){

perror("fail to exec");

exit(1);

if(getcwd(buf,max)==null){

perror("fial to get pwd");

exit(1);

printf("%s/n",buf);

return 0;

在本例中工作目錄並沒有實現。

改變程序的工作目錄

先來說說 工作目錄 的概念吧。在程式中所有以檔名引用的檔案路徑都將被解釋為當前工作目錄 檔名。比如 fd open tmp test.txt o rdonly 其實shell直譯器解釋的每乙個命令本質上都是乙個程式,基本都存放在 bin目錄下,但是沒有cd這個程式。改變程序的工作目錄函式如下 inc...

檢視程序的工作目錄

程序在哪個路徑下被執行起來哪個路徑就是程序的工作目錄 current woring directory,cwd 這個概念就是這麼簡單。比如,你在 home mac下啟動乙個程序,那麼該程序的工作目錄就是 home mac 如果你在 home mac bin下啟動同乙個程式,那麼該程序的工作目錄就變為...

vc怎樣通過程序名獲取程序的工作目錄

先用openprocess 函式將程序開啟後,利用enumproces odules 函式列舉該程序的模組,利用getmodulefilenameex 函式就能取得該程序的路徑 include include include psapi.h pragma comment lib,psapi.lib ...