0

我正在尝试做简单的 shell 作为对自己的练习。我正在编写一个函数,它应该在 PATH 中找到一个可执行文件,并返回一个指向字符串的指针,该字符串包含可执行文件的完整路径。这是我到目前为止所拥有的;

/*bunch of includes here*/

/*
 * Find executable in path, return NULL
 * if can't find.
 */
char *find_executable(char *command)
{
    const char *PATH = getenv("PATH");
    DIR *dp;
    /* get each pathname, and try to find executable in there. */
}

int main(int argc,char *argv[])
{ /* nothing intersting here ...*/
}

我想知道我应该如何分隔路径的每个部分,并在 for 循环中处理这些部分。

4

1 回答 1

3

说路径将被分隔;
您可以使用 strtok 函数生成拆分令牌。
例如

char *str = "/foo/a1/b1;/bar/a1/b1"

现在您可以将 strtok 函数用作

char delims[] = ";"  
char *result = NULL;  
result = strtok( str, delims );  
while( result != NULL ) {  
    dp = result;  
    result = strtok( NULL, delims );   
}
于 2012-05-20T06:08:57.783 回答