Windows/Linux獲取當前運行程序的絕對路徑


windows

獲取當前運行程的絕對路徑(.exe)

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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM