linux 下获取程序的绝对路径

来源:互联网 发布:成龙人品知乎 编辑:程序博客网 时间:2024/05/18 12:44

http://www.haogongju.net/art/240736


环境: 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;
}

原创粉丝点击