简体   繁体   中英

C/C++ - executable path

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 (_NSGetExecutablePath(path, &size) == 0)
    printf("executable path is %s\n", path);
else
    printf("buffer too small; need size %u\n", size);

It works, but this adds the executable name at the end.

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> ...

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

使用dirname

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

char* program_name = dirname(path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM