Linux C獲取當前工作目錄的幾種方法
阿新 • • 發佈:2021-06-26
目錄
獲取當前工作目錄有多種方式。
1. getcwd 獲取工作目錄(啟動程式的目錄)
getcwd 可以獲取當前工作目錄,但不是目標程式所在目錄,而是啟動程式的目錄。
比如,如果從shell 工作目錄/home/user
啟動目標程式(位於/home/user/workspace/testpro/debug/test
),那麼通過getcwd得到的是/home/user
。
同系列函式有3個:
getcw 呼叫者提供buf,以及指定最大長度(bytes),函式填充內容。實際路徑長度超過指定長度時,會返回NULL,errno被設定。通常路徑長度,最大不會超過系統限制_POSIX_PATH_MAX(標頭檔案<limits.h>)。
getwd 呼叫者提供buf,函式填充內容。buf長度最少應該是PATH_MAX。
get_current_dir_name 函式malloc緩衝區,呼叫者free(釋放)緩衝區。
注意:getcw不適用於開機啟動程式(未測試),參見linux下獲取程式當前目錄絕對路徑 |CSDN
#include <unistd.h>
char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);
示例
#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #ifdef _POSIX_PATH_MAX #define PATHNAME_MAX POSIX_PATH_MAX #else #define PATHNAME_MAX 1000 #endif void pr_currendir() { char buf[PATHNAME_MAX]; /* 使用getcwd獲取啟動目錄 */ if (NULL == getcwd(buf, sizeof(buf))) { fprintf(stderr, "getcwd error: %s", strerror(errno)); exit(1); } printf("current work path: %s\n", buf); char *s; /* 使用get_current_dir_name獲取啟動目錄 */ if ((s = get_current_dir_name()) == NULL) { fprintf(stderr, "getcwd error: %s", strerror(errno)); exit(1); } printf("current dir name: %s\n", s); if (s != NULL) { free(s); /* 別忘了free get_current_dir_name malloc的緩衝區 */ } }
2. readlink 獲取執行程式目錄(目標程式所在目錄)
readlink 用於讀取符號連線,並不能直接獲取當前執行程式所在目錄,而是要結合linux系統自身特點:用readlink,讀取符號連結/proc/self/exe
來獲取目標程式所在目錄。
linux程序在執行的時候,會在/proc/
目錄下存放有關程序的資訊(只存放在RAM),可以通過該偽檔案系統和核心資料結構進行互動。/proc/self/exe
就是存放的執行程式的路徑,等價與/proc/當前執行程序的pid/exe
。
#include <unistd.h> ssize_t readlink(const char *path, char *buf, size_t bufsiz);
示例
void pr_curentdir()
{
char str[PATHNAME_MAX];
char buf[PATHNAME_MAX];
snprintf(str, sizeof(str), "/proc/%d/exe", pid);
/* <=>
snprintf(str, sizeof(str), "/proc/self/exe");
*/
readlink(str, buf, sizeof(str));
printf("current work path: %s\n", buf);
}