C/C++ - executable path

前端 未结 5 770
广开言路
广开言路 2021-01-21 15:36

I want to get the current executable\'s file path without the executable name at the end.

I\'m using:

char path[1024];
uint32_t size = sizeof(path);
if (         


        
5条回答
  •  时光说笑
    2021-01-21 16:10

    For Linux:
    Function to execute system command

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

    Then we get app name

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

    Then we extract application path

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

    Do not forget to trim the line after

提交回复
热议问题