【发布时间】:2014-11-05 11:11:02
【问题描述】:
所以我必须用 C 语言构建一个程序,该程序实际上从键盘获取命令,将其拆分为存储在数组中的标记,并将这些标记用作“execv”(ubuntu 中的命令)的输入,我选择了带有参数“-a”的命令“uname”,但我被困在数组存储中,因为它只存储被拆分的令牌的第一个字母。
#include <stdio.h>
#include<stdlib.h>
#include <string.h> /*strtok strcpy*/
#include<malloc.h> /*malloc*/
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* waitpid */
#include <unistd.h> /* _exit, fork */
int main()
{
int i=0;
char *cuvinte[256]; // words
char comanda[256]; //command
printf("Introduceti comanda: "); //enter the command
fgets(comanda,sizeof(comanda),stdin); // read the command
char *c = strtok(comanda," "); // split it into tokens
while(c!=0)
{
cuvinte[i] = malloc( strlen( c ) + 1 ); // alocate memory for the array
strcpy(cuvinte[i++],c); //copying tokens into array
printf("%s\n",c); // printing them
c=strtok(NULL, " ,.!?");
}
printf("Sunt %d elemente stocate in array! \n\n",i); //no of tokens stored
printf("Primul cuvant este: \n\n\n"+*cuvinte[1]); //should print the first word
/*i got stucked here because of the tokens */
/*face un proces copil*/
pid_t pid=fork();
if (pid==0) { /* procesul copil*/
static char *argv[]={"/bin/uname","-a",NULL};
execv(argv[0],argv);
exit(127); /*in caz ca execv da fail*/
}
else { /* pid!=0; proces parinte */
waitpid(pid,0,0); /* asteapta dupa copil */
}
//getch();
return 0;
}
【问题讨论】:
-
在 C 中,您不能将字符串与
+连接。你的打印命令应该是printf("Primul cuvant este: %s\n", cuvinte[1]);