2012-10-29 33 views
0

的C++我使用NetBeans编程C++,我想要得到的可执行文件的当前绝对路径为什么我得到错误的当前目录在linux

(~/NetBeansWorkSpace/project_1/dist/Debug/GNU-Linux-x86/executableFileName)

所以我用

1,system("pwd")

2,getcwd(buffer,bufferSize)

然后点击运行按钮,但他们都得到了错误的路径:〜/ NetBeansWorkSpace/PROJECT_1

这里是惊喜,我运行的bash

cd ~/NetBeansWorkSpace/project_1/dist/Debug/GNU-Linux-x86/executableFileName

./executableFileName

我得到了正确的道路。

这是为什么?

+4

似乎你的IDE正在设置它的程序运行时的当前目录。一般来说,你不能依赖工作目录作为可执行文件的位置。 – Cameron

+0

'pwd'和'getcwd'返回当前工作目录,而不是可执行文件位置的路径... – bames53

回答

1

正如其他人所说,NetBeans在运行应用程序之前设置工作目录。如果你想获得可执行文件的工作目录,我相信下面的内容应该可以工作。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char const* *argv) { 
    char *resolved = realpath(argv[0], NULL); 
    if (resolved != NULL) { 
     char *fname = strrchr(resolved, '/'); 
     if (fname != NULL) { 
      fname[1] = '\0'; 
     } 
     printf("absolute path of %s is %s\n", argv[0], resolved); 
     free(resolved); 
    } else { 
     perror("realpath"); 
    } 
    return EXIT_SUCCESS; 
} 
+0

太棒了,非常感谢。你解决了我的问题。 –

0

NetBeans通过在导向它的路径dist/Debug/GNU-Linux-x86/前加上从~/NetBeansWorkSpace/project_1/开始您的应用程序。

打开一个shell,执行cd ~/NetBeansWorkSpace/project_1/,然后执行dist/Debug/GNU-Linux-x86/executableFileName,您将得到与从NetBeans运行应用程序相同的结果。

+0

我试过了,是的,你说得对,我看到 –

1

没什么错 - NetBeans正在运行程序,并将当前工作目录设置为项目目录(~/NetBeansWorkSpace/project_1)。

您的程序不应该依赖于当前目录与您程序所在的目录相同。如果您想查看一些获取程序绝对路径的不同方法,请参阅this thread

+0

谢谢你告诉他们之间的区别 –

0

对于Linux:
功能来执行系统命令

int syscommand(string aCommand, string & result) { 
    FILE * f; 
    if (!(f = popen(aCommand.c_str(), "r"))) { 
      cout << "Can not open file" << endl; 
      return NEGATIVE_ANSWER; 
     } 
     const int BUFSIZE = 4096; 
     char buf[ BUFSIZE ]; 
     if (fgets(buf,BUFSIZE,f)!=NULL) { 
      result = buf; 
     } 
     pclose(f); 
     return POSITIVE_ANSWER; 
    } 

然后我们得到的应用程序名称

string getBundleName() { 
    pid_t procpid = getpid(); 
    stringstream toCom; 
    toCom << "cat /proc/" << procpid << "/comm"; 
    string fRes=""; 
    syscommand(toCom.str(),fRes); 
    size_t last_pos = fRes.find_last_not_of(" \n\r\t") + 1; 
    if (last_pos != string::npos) { 
     fRes.erase(last_pos); 
    } 
    return fRes; 
} 

然后我们提取应用程序的路径

string getBundlePath() { 
    pid_t procpid = getpid(); 
    string appName = getBundleName(); 
    stringstream command; 
    command << "readlink /proc/" << procpid << "/exe | sed \"s/\\(\\/" << appName << "\\)$//\""; 
    string fRes; 
    syscommand(command.str(),fRes); 
    return fRes; 
    } 

不要忘了修整行后