命令行*args[]参数输入的C语言实现

有时需要自己实现类似于命令行参数的输入,将其存放于字符串指针数组char *arg[];

原理:

1、scanf()不会读取空格,而是将其作为一种输入完毕的标志

2、getchar()从键盘输入缓冲区读取最后一个字符,若按过回车,则最后一个字符应当是‘\n’ ,可以将次作为命令行参数输入完毕的标志

代码如下:

 1 #include <unistd.h>
 2 #include <string.h>
 3 #include <stdio.h>
 4 #include <wait.h>
 5 #include <stdlib.h>
 6 #define MAX_LINE 80
 7 
 8 int main(void){
 9 char *args[MAX_LINE/2 + 1];
10 int should_run = 1;
11 int waitFlag = 1;//flag of wait, 1 represent the father need to wait
12 while(should_run){
13   printf("myCommand(input 'exit' to exit)>>");
14   fflush(stdout);
15 
16   //read input
17   char args[10][50];
18   int num = 0;
19   int while_do = 1;
20   while(while_do){
21     if((scanf("%s", args[num])) == EOF || getchar() == '\n'){
22     while_do = 0;
23     }//delay to close input
24     num++;
25     if(strcmp(args[num-1], "&") == 0){
26       waitFlag = 0;
27     }
28 
29     if(strcmp(args[num-1], "exit") == 0){//set the flag of end
30       should_run = 0;
31       break;
32     }
33 
34   }
35   for(int i = 0;i < num;i++){
36     printf("%d", i);
37     printf("%s", args[i]);
38   }
39 
40 }
41 return 0;
42 }

 

posted @ 2023-03-22 20:59  Bai_huasheng  阅读(148)  评论(0编辑  收藏  举报