intmain()
{
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.
letdir = 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 �
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();