获取可执行文件的全路径和所属目录
主要代码:
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
浙公网安备 33010602011771号