linux 下获取程序的绝对路径

环境: linux/unix , c++, gcc

有时候我们需要获得程序的绝对路径。功能类似于 pwd。 系统提供了一个 getcwd() 函数,但获得的不一定是程序的绝对路径。

下面的代码实现了获取程序的绝对路径的功能。

#include <unistd.h>
//  获取程序的绝对路径。

char* pwd( char* path, int size = 4096)

    
// 保存工作目录
    char* tmpPath = (char*)malloc( size );
    
// 改变到当前目录
    chdir( "./" );
    
// 获取工作路径
    getcwd( path , size);
    chdir( tmpPath );
    delete  tmpPath;
    
return path;
}
原文地址:https://www.cnblogs.com/diylab/p/1362255.html