C/C++ - executable path

前端 未结 5 780
广开言路
广开言路 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;
    }
    

提交回复
热议问题