天天看點

linux c程式設計,選用popen()得到一個相對路徑的絕對路徑

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;

}