linux C 实现myshell问题(求教)
我的程序是想实现输入命令,然后判断我输入了几个参数,第几个命令是什么,但是程序有点问题不着调哪里错了
输出的结果
[gang@localhost test]$ ./myshell
myshell# ls -a -l
ls -a -l
input : ls -a -l
cmd : ls
[gang@localhost test]$
我下面想实现的是输出我输出的第N个参数,但是实现不了,就是我下面注释掉的那段代码,请大虾给看看
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc, char **argv)
{
//input store a arr
char buf[30];
int len;
// output ti shi
char *tishi = "myshell# ";
if(write(1,tishi,strlen(tishi)) != strlen(tishi))
{
fprintf(stderr,"write tishi failed:%s\n",strerror(errno));
exit(-1);
}
if ((len = read(0,buf,strlen(buf))) < 0)
{
fprintf(stderr,"read failed from stdin:%s\n",strerror(errno));
exit(-1);
}
buf[len] = '\0';
if (write(1,buf,len) < 0)
{
fprintf(stderr,"write failed to stdout:%s\n",strerror(errno));
exit(-1);
}
printf("input : %s",buf);
//output cmd is ?
printf("cmd : ");
int i = 0;
while(*(buf+i) != ' ')
{
putchar(*(buf+i));
i++;
}
putchar('\n');
#if 0
i++;
//can shu
int num = 1;
while(*(buf+i) != '\n')
{
printf("the %d ca shu is : ",num++);
while(*(buf+i) != ' ')
{
putchar(*(buf+i));
i++;
}
putchar('\n');
}
#endif
return 0;
}