Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 7d48e79739a819856b86eef354c955a6f587c0ce (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 * pfind.c - Search for a binary in $PATH.
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#ifndef PATH_MAX
#define PATH_MAX 1024
#endif


char *pfind( const char *name )
{
    char *tok;
	char *sp;
    char *path = getenv( "PATH" );
	char FullPath[PATH_MAX+1];

    if( name == NULL )
    {
        fprintf( stderr, "pfind(): Null argument.\n" );
        return NULL;
    }

    if( path == NULL || strlen( path ) <= 0 )
    {
        fprintf( stderr, "Unable to get $PATH.\n" );
        return NULL;
    }

    // The value return by getenv() is readonly */
    path = strdup( path );

    tok = strtok_r( path, ":", &sp );
    while( tok != NULL )
    {
        //strcpy( FullPath, tok );
        //strcat( FullPath, "/" );
        //strcat( FullPath, name );
		snprintf(FullPath, sizeof(FullPath) - 1, "%s/%s", tok, name);

        if( access( FullPath, X_OK | R_OK ) == 0 )
        {
            free( path );
            return strdup(FullPath);
        }

        tok = strtok_r( NULL, ":", &sp );
    }

    free( path );
    return NULL;
}

#ifdef BUILD_WITH_MAIN
int main( int argc, char **argv )
{
   int i;
   char *fullpath;

   for( i=1; i<argc; i++ )
   {
      fullpath = pfind( argv[i] );
      if( fullpath == NULL )
        printf( "Unable to find %s in $PATH.\n", argv[i] );
      else 
        printf( "Found %s @ %s.\n", argv[i], fullpath );
   }
}
#endif

Back to the top