簡體   English   中英

為什么我在Linux的C ++中得到錯誤的當前目錄

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

我使用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正在運行您的程序,當前工作目錄設置為項目目錄( ~/NetBeansWorkSpace/project_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;
}

NetBeans通過在路徑dist/Debug/GNU-Linux-x86/前面添加前綴來從~/NetBeansWorkSpace/project_1/啟動應用程序。

打開一個shell,執行cd ~/NetBeansWorkSpace/project_1/ ,然后執行dist/Debug/GNU-Linux-x86/executableFileName ,您將獲得與從NetBeans運行應用程序相同的結果。

對於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;
    }

不要忘記修剪線后

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM