Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get path to current exe file on Linux? [duplicate]

Tags:

c++

path

exe

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?

like image 946
user1519221 Avatar asked May 29 '14 21:05

user1519221


People also ask

How do you copy a file path in Linux?

On Linux and Unix operating systems, the cp command is used for copying files and directories. If the destination file exists, it will be overwritten. To get a confirmation prompt before overwriting the files, use the -i option.

How do I find the path of a file in Linux?

Firstly, we use the dirname command to find the directory in which a file is located. Then we change the directory using the cd command. Next, we print the current working directory using the pwd command. Here, we have applied the -P option to show the physical location instead of the symbolic link.

How do I find the absolute path of a file?

You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.

How do I find absolute path in Ubuntu?

To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.


1 Answers

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);
}
like image 108