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

发布时间 2023-03-22 21:16:59作者: Bai_huasheng

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

原理:

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

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

代码如下:

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <wait.h>
#include <stdlib.h>
#define MAX_LINE 80

int main(void){
char *args[MAX_LINE/2 + 1];
int should_run = 1;
int waitFlag = 1;//flag of wait, 1 represent the father need to wait
while(should_run){
  printf("myCommand(input 'exit' to exit)>>");
  fflush(stdout);

  //read input
  char args[10][50];
  int num = 0;
  int while_do = 1;
  while(while_do){
    if((scanf("%s", args[num])) == EOF || getchar() == '\n'){
    while_do = 0;
    }//delay to close input
    num++;
    if(strcmp(args[num-1], "&") == 0){
      waitFlag = 0;
    }

    if(strcmp(args[num-1], "exit") == 0){//set the flag of end
      should_run = 0;
      break;
    }

  }
  for(int i = 0;i < num;i++){
    printf("%d", i);
    printf("%s", args[i]);
  }

}
return 0;
}