C/C++ - executable path

人盡茶涼 提交于 2019-12-31 02:51:07

问题


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.


回答1:


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




回答2:


Use dirname.




回答3:


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



回答4:


char* program_name = dirname(path);



回答5:


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



来源:https://stackoverflow.com/questions/8579065/c-c-executable-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!