Hi!
I'm trying to find an executable in the users environment PATH, let's say I want to search for "foo.exe", how can I traverse getenv ("PATH");
Printable View
Hi!
I'm trying to find an executable in the users environment PATH, let's say I want to search for "foo.exe", how can I traverse getenv ("PATH");
The which command from GnuWin32 does just this; I suggest looking at its source code.
Which for Windows
Tim S.
The easiest way, since (on Windows at least) the system will auto-search the path, is to try to open the file. If fopen() succeeds the file is there. The function can then close the file and return TRUE or 1. If fopen() fails your function should return FALSE or 0.
You can try getting the path, splitting it up into its respective directories, appending the filename to each directory, and then test to see if the file exists? To split the path, you can use strtok, like so:
Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char *path = getenv( "PATH" );
char *dir;
for ( dir = strtok( path, ":" ); dir; dir = strtok( NULL, ":" ) ) {
puts( dir );
}
return 0;
}
/*
Output:
$ gcc -ansi -pedantic -Wall main.c
$ ./a.out
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/texbin
/usr/X11/bin
/usr/X11R6/bin
$
*/
Thanks kmess :)
Any time :)