随笔 - 491  文章 - 0  评论 - 97  阅读 - 239万

获取可执行文件的全路径和所属目录

主要代码:

int GetCurFilePath(char *lpOut)                 // get full path of the executable file
{
    char chPath[BUFSIZ] = {0};
    int nRetVal = readlink("/proc/self/exe", chPath, sizeof(chPath)); // get full path of the current-executable file
    if(nRetVal < 0)
    {
        strcpy(lpOut, ".");
        return -1;
    }
    else
    {
        strcpy(lpOut, chPath);
        return 0;
    }
}
 
int GetCurDir(char *lpOutDir)                       // get directory-path of current executable-file
{
    char    chPath[BUFSIZ] = { 0 };
    if( GetCurFilePath(chPath) < 0 )
        return - 1;
    dirname(chPath);                                    // dirname will change value of "chPath"(contain result)
    strcpy(lpOutDir, chPath);                       // copy result to out-param
 
    return 0;
}


上面的BUFSIZ是库函数中定义的宏,值为8192

可能需要的头文件有:

#include <unistd.h> : readlink
#include <string.h> :strcpy ...
#include <libgen.h> :dirname

posted on   清清飞扬  阅读(1001)  评论(0编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示