Debian Codegraph @

listings/chapter-7/get-exe-path.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <limits.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <unistd.h>
11
12 /* Finds the path containing the currently-running program executable.
13 The path is placed into BUFFER, which is of length LEN. Returns
14 the number of characters in the path, or -1 on error. */
15
16 size_t get_executable_path (char* buffer, size_t len)
17 {
18 char* path_end;
19 /* Read the target of /proc/self/exe. */
20 if (readlink ("/proc/self/exe", buffer, len) <= 0)
21 return -1;
22 /* Find the last occurence of a forward slash, the path separator. */
23 path_end = strrchr (buffer, '/');
24 if (path_end == NULL)
25 return -1;
26 /* Advance to the character past the last slash. */
27 ++path_end;
28 /* Obtain the directory containing the program by truncating the
29 path after the last slash. */
30 *path_end = '\0';
31 /* The length of the path is the number of characters up through the
32 last slash. */
33 return (size_t) (path_end - buffer);
34 }
35
36 int main ()
37 {
38 char path[PATH_MAX];
39 get_executable_path (path, sizeof (path));
40 printf ("this program is in the directory %s\n", path);
41 return 0;
42 }