您的位置:首页 > 运维架构 > Linux

linux 下获取程序的绝对路径

2008-12-25 13:39 253 查看
环境: 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: