6d1b41c180c5c819414cda05cace0ba3e45d75af
[rsync/rsync.git] / popt / findme.c
1 /* (C) 1998 Red Hat Software, Inc. -- Licensing details are in the COPYING
2    file accompanying popt source distributions, available from 
3    ftp://ftp.redhat.com/pub/code/popt */
4
5 #include "system.h"
6 #include "findme.h"
7
8 const char * findProgramPath(const char * argv0) {
9     char * path = getenv("PATH");
10     char * pathbuf;
11     char * start, * chptr;
12     char * buf;
13
14     /* If there is a / in the argv[0], it has to be an absolute
15        path */
16     if (strchr(argv0, '/'))
17         return xstrdup(argv0);
18
19     if (!path) return NULL;
20
21     start = pathbuf = alloca(strlen(path) + 1);
22     buf = malloc(strlen(path) + strlen(argv0) + 2);
23     strcpy(pathbuf, path);
24
25     chptr = NULL;
26     do {
27         if ((chptr = strchr(start, ':')))
28             *chptr = '\0';
29         sprintf(buf, "%s/%s", start, argv0);
30
31         if (!access(buf, X_OK))
32             return buf;
33
34         if (chptr) 
35             start = chptr + 1;
36         else
37             start = NULL;
38     } while (start && *start);
39
40     free(buf);
41
42     return NULL;
43 }