C语言:获取当前路径(readlink()函数)

程序:

#include 
#include 
char * get_exe_path( char * buf, int count)
{
    int i;
    int rslt = readlink("/proc/self/exe", buf, count - 1);
    if (rslt < 0 || (rslt >= count - 1))
    {
        return NULL;
    }
    buf[rslt] = '\0';
    for (i = rslt; i >= 0; i--)
    {
        if (buf[i] == '/')
        {
            buf[i + 1] = '\0';
            break;
        }
    }
    return buf;
}

int main(int argc, char ** argv)
{
    char path[1024];
    printf("%s\n", get_exe_path(path, 1024));
    return 0;
}

运行:

root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file# gcc -o 2 2.c 
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file# ./2
/mnt/hgfs/Ubuntu12.04-share/test/2_file/
root@ubuntu:/mnt/hgfs/Ubuntu12.04-share/test/2_file#

参考链接:
https://blog.csdn.net/feixue0000/article/details/14167333

https://blog.csdn.net/ai2000ai/article/details/52459952

你可能感兴趣的:(C/C++)