getcwd()
是一個 C 語言標準庫函數,用于獲取當前工作目錄的絕對路徑
首先,你需要包含頭文件 unistd.h
。然后,使用 getcwd()
函數,將結果存儲在一個字符數組中。注意,數組的大小應該至少為路徑的最大長度,包括空終止符。
下面是一個簡單的示例:
#include <iostream>
#include <unistd.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
std::cout << "Current working directory: " << cwd << std::endl;
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
在這個示例中,我們首先定義了一個字符數組 cwd
,其大小至少為 PATH_MAX
。然后,我們調用 getcwd()
函數,將結果存儲在 cwd
中。如果函數成功執行(返回非空指針),我們將輸出當前工作目錄。否則,我們將使用 perror()
函數輸出錯誤信息。