This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <linux/limits.h>
#include <libgen.h>
int main()
{
char exe[PATH_MAX], real_exe[PATH_MAX];
ssize_t r;
char *dir;
if ((r = readlink("/proc/self/exe", exe, PATH_MAX)) < 0)
exit(1);
if (r == PATH_MAX)
r -= 1;
exe[r] = 0;
if (realpath(exe, real_exe) == NULL)
exit(1);
dir = dirname(real_exe);
puts(dir);
}
If the executable file that the current process is executing can be found searching $PATH, this is easier, but the general case can still be handled by examining where the symlink file /proc/self/exe points to.
import System.Environment (getExecutablePath)
import System.FilePath.Windows
import System.IO.Unsafe (unsafePerformIO)
dir = unsafePerformIO (takeDirectory `fmap` getExecutablePath)
This uses unsafePerformIO which I assume to be safely used here because the executable path can be considered as constant.
my $dir = path($EXECUTABLE_NAME)->parent;
let dir = std::env::current_exe()?
.canonicalize()
.expect("the current exe should exist")
.parent()
.expect("the current exe should be a file")
.to_string_lossy()
.to_owned();
Rust doesn't represent paths as Strings, so we need to convert the Path returned from Path::parent. This code chooses to do this lossily, replacing characters it doesn't recognize with �
programming-idioms.org