There are several ways to set a "starting point", i.e. the table of contents, knowing that we can calculate all the paths we need to the configuration files, etc.
This may be the environment variable, the home directory of the user who launched the program, and the directory in which the executable code is located.
When the system starts, the first argument passes to the program its name, as entered by the user in the shell (or what the programmer indicated when calling it through exec ).
If the name of the program being started does not contain an absolute or relative (relative to the current (where its name is typed from) directory) path, then the system looks for a directory with the program code in the PATH environment variable, where the symbols : listed through the symbol :
Using this knowledge, you can easily write a couple of functions that, after getting the name from the command line parameter, return the directory in which the program is running.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <unistd.h> char * srcpath (const char *pgm) { char *path = getenv("PATH"), dir[PATH_MAX], *p; if (path) for (p = path; *p; *p ? p++ : p) { char *t = dir, *e = dir + PATH_MAX - 1; while (*p && *p != ':' && t < e) *t++ = *p++; if (snprintf(t, e - t, "/%s", pgm) < e - t && access(dir, R_OK | X_OK) == 0) return strndup(dir, t - dir); } return 0; } char * srcdir (const char *av0) { const char *pgm = strrchr(av0, '/'); return pgm ? strndup(av0, pgm - av0) : srcpath(av0); } int main (int ac, char *av[]) { char *dir; for (; *av; av++) { printf("%s : %s\n", av[0], dir = srcdir(av[0])); free(dir); } return puts("End") == EOF; }
At least in Linux (starting from 2.2) in the / proc directory for each process there is a file (actually a symbolic link) /proc/[pid]/exe containing the full path to the executable file.
Let's write a similar function that extracts the directory from /proc :
char * linux_srcdir () { char buf[PATH_MAX]; int n = readlink("/proc/self/exe", buf, PATH_MAX); return n > 0 ? buf[n] = 0, strndup(buf, strrchr(buf, '/') - buf) : 0; }
./Release,./Debugetc - PinkTuxargv[0](and whatgetcwd()will say) - PinkTux