【问题标题】:Splitting PATH environ variable into individual filepaths将 PATH 环境变量拆分为单独的文件路径
【发布时间】:2012-05-27 02:48:31
【问题描述】:

我正在尝试做简单的 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 循环中处理这些部分。

【问题讨论】:

  • 如果你要写一个shell,你真的应该首先掌握字符串解析。
  • @jamesdlin 我尝试编写 shell 的原因是在练习时有一个目标。否则,我会迷路和无聊。我正在尝试完成应用程序的同时学习。

标签: c path environment-variables


【解决方案1】:

说路径将用 ;
分隔 您可以使用 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 );   
}

【讨论】:

  • 在 linux 上的路径通常由冒号而不是分号分隔。
猜你喜欢
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 2014-03-24
相关资源
最近更新 更多