所以我必须在 C 中构建一个程序,实际上从键盘获取命令,将其拆分为存储在数组中的标记,并将这些标记用作“execv”(ubuntu 中的命令)的输入,我选择了使用参数“-a”命令“uname”,但我被困在数组存储中,因为它只存储被分割的 token 的第一个字母。
#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;
}
最佳答案
我认为您的问题是 printf("Primul cuvant este:\n\n\n"+*cuvinte[1]);
语句。这将取消引用 cuvinte
中第二项的第一个字符。我认为你想做的是 printf("Primul cuvant este: %s\n\n\n",cuvinte[0]);
。
关于ubuntu 的 C 程序解析器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26755741/