c - 将 '\0' 放在字符串中间以提前终止它是行不通的
问题描述
我想创建一个程序,它会接受一个 Linux 输入命令,比如 pwd -P 并用它做一些事情。我想要做的是把它们放在一个字符串中,其中空格''字符被替换为空终止符'\0',所以它看起来像“pwd\0-P”。然后,我可以让 array[0] 指向字符串的开头,并让 array[1] 指向 '\0' 之后的部分,所以我会有 2 个单独的字符串 -> array[0] = " pwd" 和数组 [1] = "-P"。这就是我可以使用 exec(array[0],array);
我的问题是,当我这样做时,空终止符不会在“pwd”之后终止字符串,并且我的字符串最终变成“pwd-P”,其中没有空格。
我正在做这一切的字符串是“检查”
int main(int argc, char * argv[]) {
char ch;
pid_t pid;
int i=0;
int flag = 0;
int word = 0;
int count = 0;
char check[100],temp[100];
char * array[100];
printf("Your Command> ");
strcpy(check,"");
//command stuff
array[word] = check;
temp[i]='\0';
while((ch = getchar()) != '\n'){
count = count+1;
if(ch != '&' && ch != ' '){
strcpy(temp,&ch);
strcat(check,temp);
}
else if(ch == ' '){
check[count] = '\0';
word = word+1;
array[word] = &check[count];
}
else if(ch == '&'){
flag =1;
check[count] = 0;
}
}
//end of command stuff
if(flag!=1){
check[count] = '\0';
}
word = word+1;
puts(check);
array[word] = &check[count];
//fork process stuff
if((pid = fork())==0){
printf("hello from child\n");
printf("%s\n",array[0]);
printf("%s\n",array[1]);
printf("%s\n",array[2]);
execvp(array[0], array);
}
else{
if(flag == 0){
wait(NULL);
printf("hello from parent\n");
}
else{
printf("hello from parent (no wait)\n");
}
}
return(EXIT_SUCCESS);
}
解决方案
推荐阅读
- visual-studio-code - 在 VSCode 中使用远程 SSH 时“必须连接到终端”
- reactjs - 在 gh-pages 上托管多页反应应用程序时出现 404 错误
- digital-signature - PdfSharp 撰写带有两个数字签名的 pdf
- node.js - Express JS 和 CoinPayments:无法获取 IPN 通知请求的请求正文
- python-3.x - 在python中调用单例初始化函数
- python-3.x - 在 Python 中将字符串转换为我的数据类型
- django - 使用 django-adm-interface 或通过覆盖 base_site.html 更改 Django 管理徽标不起作用
- apache-kafka - __consumer_offsets 主题中的 Tombstone 从未删除。为什么?
- python - PYQT5、Python、QTableView:如何仅在最后一列添加数据
- java - 有状态服务有什么好处吗