在 Linux 系統程式開發中,需取得當前使用者家目錄路徑時,標準庫函式 getenv() 提供最簡潔方案。
#include <stdlib.h> // getenv() 原型
#include <stdio.h>
int main() {
char *path = getenv("HOME");
if (path) {
printf("Home directory: %s\n", path);
} else {
fprintf(stderr, "環境變數 HOME 未設定\n");
return 1;
}
return 0;
}
stdlib.h(非 unistd.h)HOME 由登入 Shell 依據 /etc/passwd 自動設定。NULL。getenv() 在多執行緒環境下非安全,建議使用 secure_getenv()(glibc 2.17+)或自行加鎖。#include <pwd.h>
#include <stdio.h>
int main() {
struct passwd *pw = getpwnam("username"); // 指定使用者名
if (pw) {
printf("Home: %s\n", pw->pw_dir);
}
return 0;
}
此法直接查詢 /etc/passwd,不依賴環境變數,適合服務程式或切換身分情境。