C/C++ - executable path

前端 未结 5 769
广开言路
广开言路 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 15:54

    Best solution for Ubuntu!!

    std::string getpath() {
      char buf[PATH_MAX + 1];
      if (readlink("/proc/self/exe", buf, sizeof(buf) - 1) == -1)
      throw std::string("readlink() failed");
      std::string str(buf);
      return str.substr(0, str.rfind('/'));
    }
    
    int main() {
      std::cout << "This program resides in " << getpath() << std::endl;
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-21 16:03

    Use dirname.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-21 16:12
    char* program_name = dirname(path);
    
    0 讨论(0)
  • 2021-01-21 16:19

    dirname(path); should return path without executable after you acquire path with, that is on Unix systems, for windows you can do some strcpy/strcat magic.

    For dirname you need to include #include <libgen.h>...

    0 讨论(0)
提交回复
热议问题