2012-05-20 116 views
0

我正在嘗試對自己做一個簡單的shell作爲練習。我正在編寫一個函數,該函數應該在PATH中找到可執行文件,並返回一個指向包含可執行文件完整路徑的字符串的指針。這是我迄今爲止;將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循環中處理這些部分。

+0

考慮['的strtok()'](http://pubs.opengroup.org/onlinepubs/009604599/functions/strtok.html )和[示例](http://www.cplusplus.com/reference/clibrary/cstring/strtok/) – jedwards

+1

如果您要編寫shell,那麼您應該首先了解字符串解析。 – jamesdlin

+1

@jamesdlin我試圖編寫一個shell的原因是在練習時有一個目標。否則,我會迷失和無聊。我在嘗試完成應用程序時嘗試學習。 – yasar

回答

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); 
} 
+0

在Linux上,路徑通常由冒號而不是分號分隔。 –