我正在使用c创建自己的shell但我一直收到错误,我认为这涉及使用 strtok
和 strcat
. 请注意 path
和 userInput
是全局字符串 .
int myFunction()
{
char *possiblePaths = getenv(PATH);
path = strtok(possiblePaths,":");
path = strcat(path,"/");
path = strcat(path, userInput);
while(path != NULL)
{
//other code
path = strtok(NULL,":");
path = strcat(path,"/");
path = strcat(path, userInput);
}
return 1;
}
getenv给了我一个字符串,
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/texbin
我当时想要做的是基于 ':'
标记字符串,然后连接 '/'
加上我的全局变量 userInput
. 输出应该看起来像,
/opt/local/bin/userInput
然后下一次我会得到循环
/opt/local/sbin/userInput
不幸的是我得到以下内容
/opt/local/bin/userInput
userInput/userInput
/userInput/userInput
/userInput/userInput
我的第一个 strtok
和 strcat
给了我正确的结果 . 但是 /userInput
将继续循环,直到我遇到分段错误 . 我很确定我的错误与使用 strtok
和 strcat
混合指针有关,但我无法弄清楚如何解决它 .
1 回答
根据C标准(7.22.4.6 getenv函数)
标准C函数
strtok
将传递给函数的原始字符串更改为参数 .您可以使用标准C函数
strchr
来查找字符':'
,然后使用另一个标准函数memcpy
在字符数组中复制找到的字符串,然后使用必需的字符串附加它 .