This language bar is your friend. Select your favorite languages!

Idiom #107 Get folder containing current program

Assign to string dir the path of the folder containing the currently running executable.
(This is not necessarily the working directory, though.)

let dir = std::env::current_exe()?
    .expect("the current exe should exist")
    .expect("the current exe should be a file")
#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)
    if (r == PATH_MAX)
	r -= 1;
    exe[r] = 0;
    if (realpath(exe, real_exe) == NULL)
    dir = dirname(real_exe);
dir = AppDomain.CurrentDomain.BaseDirectory;
import std.path;
void main(string[] args) {
    string dir = args[0].dirName;
import "os"
import "path/filepath"
programPath := os.Args[0]
absolutePath, err := filepath.Abs(programPath)
if err != nil {
	return err
dir := filepath.Dir(absolutePath)
import System.Environment (getExecutablePath)
import System.FilePath.Windows
dir <- takeDirectory `fmap` getExecutablePath
import System.Environment (getExecutablePath)
import System.FilePath.Windows
import System.IO.Unsafe (unsafePerformIO)
dir = unsafePerformIO (takeDirectory `fmap` getExecutablePath)
const path = require('path');

const currentFolder = path.resolve();
dir = arg[1]
$dir = realpath(dirname(__FILE__));
dir := extractfilepath(paramstr(0));
use English qw($EXECUTABLE_NAME);
use Path::Tiny qw(path);
my $dir = path($EXECUTABLE_NAME)->parent;
import os
dir = os.path.dirname(os.path.abspath(__file__))
dir = __dir__

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

Related idioms