Skip to content

Instantly share code, notes, and snippets.

@mburr
Created June 2, 2014 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mburr/0ac468b65532d46b1681 to your computer and use it in GitHub Desktop.
Save mburr/0ac468b65532d46b1681 to your computer and use it in GitHub Desktop.
mburr / prtpath.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#ifndef _WIN32
/*
get strdup() and strtok_r() from other snippets if needed
*/
char* strdup(char const* s)
{
int len = 0;
char* pResult = NULL;
assert( s != NULL);
len = strlen( s);
pResult = malloc( len+1);
if (pResult) {
strcpy( pResult, s);
}
return pResult;
}
/*
* public domain strtok_r() by Charlie Gordon
*
* from comp.lang.c 9/14/2007
*
* http://groups.google.com/group/comp.lang.c/msg/2ab1ecbb86646684
*
* (Declaration that it's public domain):
* http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c
*/
char* strtok_r(
char *str,
const char *delim,
char **nextp)
{
char *ret;
if (str == NULL)
{
str = *nextp;
}
str += strspn(str, delim);
if (*str == '\0')
{
return NULL;
}
ret = str;
str += strcspn(str, delim);
if (*str)
{
*str++ = '\0';
}
*nextp = str;
return ret;
}
#endif
#ifdef _WIN32
static char const* path_separators=";";
#else
static char const* path_separators=":";
#endif
int main( int argc, char** argv)
{
char* pPath;
char const* envvar = "PATH";
if (argc > 1) {
envvar = argv[1];
}
pPath = getenv(envvar);
if (!pPath) pPath = "";
pPath = strdup( pPath);
if (!pPath) {
return 1;
}
if (pPath!=NULL) {
char* context = NULL;
char* pDir = NULL;
for (pDir = strtok_r( pPath, path_separators, &context);
pDir != NULL;
pDir = strtok_r( NULL, path_separators, &context)) {
printf("%s\n", pDir);
}
}
free( pPath);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment