现在的位置: 首页 > 综合 > 正文

linux c编程,选用popen()得到一个相对路径的绝对路径

2017年01月20日 ⁄ 综合 ⁄ 共 450字 ⁄ 字号 评论关闭

linux c编程,得到一个相对路径的绝对路径,下面的程序很简单,可以将其封装成一个函数,工作中有时候会用到。

 

#include <iostream>
using namespace std;
#include <unistd.h>
#include <cstring>

int main()
{
 string dir_path = "./../../";          //相对路径
 std::string command = "cd "+dir_path + "; pwd;";
    FILE *pp=NULL;
    if( (pp = popen(command.c_str(), "r")) == NULL )
    {  
        return -1;
    }  
 
 char buf[333] = {0};
    fgets(buf, sizeof(buf), pp);     

printf("%s",buf); // 打印绝对路径
    pclose(pp);
 

// 完成任务后发现当前的绝对路径是没有变的
 system("pwd");   
 return 0;
}

抱歉!评论已关闭.