Portál AbcLinuxu, 9. května 2025 23:14
/proc/self/exe
ukazuje na aktuální binárku...
#include <limits.h> #include <stdio.h> #include <string.h> #include <unistd.h> /* Finds the path containing the currently running program executable. The path is placed into BUFFER, which is of length LEN. Returns the number of characters in the path, or -1 on error. */ size_t get_executable_path (char* buffer, size_t len) { char* path_end; /* Read the target of /proc/self/exe. */ if (readlink ("/proc/self/exe", buffer, len) <= 0) return -1; /* Find the last occurrence of a forward slash, the path separator. */ path_end = strrchr (buffer, '/'); if (path_end == NULL) return -1; /* Advance to the character past the last slash. */ ++path_end; /* Obtain the directory containing the program by truncating the path after the last slash. */ *path_end = '\0'; /* The length of the path is the number of characters up through the last slash. */ return (size_t) (path_end - buffer); } int main () { char path[PATH_MAX]; get_executable_path (path, sizeof (path)); printf ("this program is in the directory %s\n", path); return 0; }
strrchr
na bufferu hned po readlink
? Mě se to nezdá:
readlink() does not append a null byte to buf.
int main(int argc, char* argv[]) { printf("%s\n", argv[0]) return 0; }
#include <libgen.h> int main(int argc, char* argv[]) { printf("%s\n", dirname(argv[0])) return 0; }argv[0] mi připadá mnohem portabilnější než /proc (který třeba nemusí být ani na všech Linuxových instalacích, o jiných unix-like OS či win/dos ani nemluvě).
#include <stdio.h> int main(int argc,char** argv) { int i; for(i=0;i<argc;i++) printf("ARG %d: %s\n", i, argv[i]); return 0; }
lubos@ares ~ $ ./test ARG 0: ./testTomu říkáte absolutní cesta?
$0
na funkční cestu k němu.
/proc/self/exe
.
Navíc je potřeba mít na paměti, že na otázku "ve kterém adresáři se nachází tento soubor" nemusí být jednoznačná odpověď nebo dokonce může odpověď znít "v žádném"…
PATH
, jen jménem, bude v argv[0]
jen to jméno.
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.