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?
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.
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.
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.
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/.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With