これがSSCCE(短い、自己完結型、正しい例)です。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
enum { MAXARGS = 32 };
enum { MAXPATHLEN = 1024 };
char *pathsarray[MAXARGS];
static void add_path(char **dir, const char *begin, const char *end)
{
if (end == begin)
{
begin = ".";
end = begin + 1;
}
size_t len = end - begin;
*dir = malloc(len + 1);
memmove(*dir, begin, len);
(*dir)[len] = '\0';
printf("Found: %s\n", *dir); // Debug
}
/* Split path into components - ignore empty elements */
static size_t tokenizeEnvPaths(const char *path, char **dirs, size_t max_dirs)
{
const char *begin = path;
const char *end;
size_t num_dirs = 0;
while (num_dirs < max_dirs && (end = strchr(begin, ':')) != 0)
{
add_path(&dirs[num_dirs++], begin, end);
begin = end + 1;
}
if (num_dirs < max_dirs && *begin != '\0')
add_path(&dirs[num_dirs++], begin, begin + strlen(begin));
return num_dirs;
}
int main(void)
{
const char *path = getenv("PATH");
size_t ndirs = tokenizeEnvPaths(path, pathsarray, MAXARGS);
for (size_t i = 0; i < ndirs; i++)
{
if (pathsarray[i] != NULL)
{
char buffer[MAXPATHLEN];
snprintf(buffer, sizeof(buffer), "%s/%s", pathsarray[i], "ls");
fprintf(stderr, "---%s\n", pathsarray[i]);
}
}
return(0);
}
出力例:
$ PATH=:$PATH ./sp
Found: .
Found: /Users/jleffler/bin
Found: /usr/informix/11.70.FC6/bin
Found: /usr/gcc/v4.7.1/bin
Found: /usr/informix/11.70.FC6
Found: /Users/jleffler/perl/v5.16.0/bin
Found: /usr/local/bin
Found: /usr/bin
Found: /bin
Found: /usr/gnu/bin
Found: /usr/sbin
Found: /sbin
---./ls
---/Users/jleffler/bin/ls
---/usr/informix/11.70.FC6/bin/ls
---/usr/gcc/v4.7.1/bin/ls
---/usr/informix/11.70.FC6/ls
---/Users/jleffler/perl/v5.16.0/bin/ls
---/usr/local/bin/ls
---/usr/bin/ls
---/bin/ls
---/usr/gnu/bin/ls
---/usr/sbin/ls
---/sbin/ls
$