Logo

Programming-Idioms

  • Java
  • Pascal
  • Dart
  • Python

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.)

from pathlib import Path
dir = str(Path(__file__).parent)
import os
dir = os.path.dirname(os.path.abspath(__file__))
dir := extractfilepath(paramstr(0));
uses SysUtils;
dir := GetCurrentDir;
#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.

New implementation...
< >
programming-idioms.org