Directory Of Executable


frozen

Still Fresh
Joined
Jul 20, 2009
Messages
36
Hi

What is the simplest way to determine the directory (full path) of the currently running executable, on the Wiz?

Thanks,
frozen
 
In C/C++ the first argument is usually the complete path to this executable.

Edit: There is also getcwd().
 
I have not tested it on the Wiz yet, but it should work since the Wiz is running Linux, too: http://autopackage.org/docs/binreloc/
 
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
	char path[1024];
	memset(path, 0, 1024);

	if (argv[0][0] == '/') {
		// argv[0] contains the full path
		strncpy(path, argv[0], strrchr(argv[0], '/') - argv[0]);
	} else if (strrchr(argv[0], '/')) {
		// argv[0] contains a relative path
		getcwd(path, 1024);
		strcat(path, "/");
		strncat(path, argv[0], strrchr(argv[0], '/') - argv[0]);
	} else {
		// argv[0] contains no path
		char *envpath = getenv("PATH");
		char *pch = strtok(envpath, ":");
		while (pch) {
			strcpy(path, pch);
			strcat(path, "/");
			strcat(path, argv[0]);
			if (access(path, F_OK) == 0) {
				strcpy(path, pch);
				break;
			}
			pch = strtok(NULL, ":");
		}
	}

	printf("The full path to this program is \"%s\"\n", path);

	return 0;
}

This is just hastily thrown together, you should really check that the strings will fit into the buffer (or better, dynamically allocate the buffer to the required size), but it does show how to get an absolute path in linux.

You could also extend it to remove '.' and '..' from the resulting path if desired. (eg. /home/you/some/folder/../../different/../folder -> /home/you/folder).
 
An easier way (on Linux) to do this is so:

Code:
#include <stdio.h>
#include <limits.h>

int main(int argc, char *argv[])
{
    char buf[PATH_MAX];
    printf("Read link returns: %d\n", readlink("/proc/self/exe", buf, PATH_MAX));
    printf("Result: %s\n", buf);
    printf("Dir name is: %s\n", dirname(buf));
}

Result:

Read link returns: 6
Result: /tmp/t
Dirname is: /tmp
 
Yeah, that's probably better if you're targeting a specific system like the Wiz. :)

If you need it to be more portable though, use some variation on the one I posted. ;)
 
Back
Top