8

The code below gives current path to exe file on Linux:

#include <iostream>
std::string getExePath()
{
  char result[ PATH_MAX ];
  ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
  return std::string( result, (count > 0) ? count : 0 );
}
int main()
{
  std::cout << getExePath() << std::endl;  
  return 0;
}

The problem is that when I run it gives me current path to exe and name of the exe, e.g.:

/home/.../Test/main.exe

I would like to get only

/home/.../Test/

I know that I can parse it, but is there any nicer way to do that?

user1519221
  • 631
  • 5
  • 13
  • 24
  • Your title is a bit misleading. The question is really about getting a directory given a file name. The fact that the file happens to be your executable is not important. – MSalters May 29 '14 at 23:12
  • See also e.g. http://stackoverflow.com/questions/10364877/c-how-to-remove-filename-from-path-string/10364907#10364907 – MSalters May 29 '14 at 23:14

1 Answers1

21

dirname is the function you're looking for.

#include <libgen.h>         // dirname
#include <unistd.h>         // readlink
#include <linux/limits.h>   // PATH_MAX

char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
const char *path;
if (count != -1) {
    path = dirname(result);
}
gregpaton08
  • 383
  • 3
  • 7