windows
GetModuleFileNameA()函數獲取絕對路徑,不過文件路徑中的反斜杠需要進行替換。
char szFilePath[MAX_PATH+1]; GetModuleFileNameA(NULL, szFilePath, MAX_PATH);
linux
1. Shell 版本 #獲取當前腳本所在絕對路徑 cur_dir=$(cd "$(dirname "$0")"; pwd) 2. C語言版本 方法一、用realpath函數。這種方法用於開機啟動程序獲取自身目錄會出錯 char current_absolute_path[MAX_SIZE]; //獲取當前目錄絕對路徑 if (NULL == realpath("./", current_absolute_path)) { printf("***Error***\n"); exit(-1); } strcat(current_absolute_path, "/"); printf("current absolute path:%s\n", current_absolute_path); 方法二、用getcwd函數。這種方法用於開機啟動程序獲取自身目錄會出錯 char current_absolute_path[MAX_SIZE]; //獲取當前目錄絕對路徑 if (NULL == getcwd(current_absolute_path, MAX_SIZE)) { printf("***Error***\n"); exit(-1); } printf("current absolute path:%s\n", current_absolute_path); 方法三、用readlink函數。這種方法最可靠,可用於開機啟動程序獲取自身目錄 char current_absolute_path[MAX_SIZE]; //獲取當前程序絕對路徑 int cnt = readlink("/proc/self/exe", current_absolute_path, MAX_SIZE); if (cnt < 0 || cnt >= MAX_SIZE) { printf("***Error***\n"); exit(-1); } //獲取當前目錄絕對路徑,即去掉程序名 int i; for (i = cnt; i >=0; --i) { if (current_absolute_path[i] == '/') { current_absolute_path[i+1] = '\0'; break; } } printf("current absolute path:%s\n", current_absolute_path);
