为什么我在Linux的C 中获得错误的当前目录

why I get the wrong current directory in C++ of linux

本文关键字:错误 当前目录 Linux 为什么      更新时间:2023-10-16

我使用NetBeans来编程C ,我想获得可执行文件的当前绝对路径

(~/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

我得到了正确的道路。

这是为什么???

正如其他所有人所说的那样,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] = '';
        }
        printf("absolute path of %s is %sn", argv[0], resolved);
        free(resolved);
    } else {
        perror("realpath");
    }
    return EXIT_SUCCESS;
}

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

您的程序不应取决于当前目录与程序所在的目录相同。如果您想查看一些不同的方法来获取程序的绝对路径。

NetBeans通过将路径dist/Debug/GNU-Linux-x86/的前缀启动~/NetBeansWorkSpace/project_1/启动您的应用程序。

打开外壳,执行CD ~/NetBeansWorkSpace/project_1/,然后做dist/Debug/GNU-Linux-x86/executableFileName,您将获得相同的结果,就像您从NetBeans运行了应用程序。

for 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(" nrt") + 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;
    }

不要忘记在

之后修剪线