首页 > 解决方案 > 从文本文件中读取命令并依次执行

问题描述

所以我被告知要编写一个程序,其中程序应该读取并执行来自stdin. 每个命令及其参数(如果有)将出现在单独的行上。我的程序可以满足他们的需要,但前提是我编写./sequence text.file./sequence < text.file text.file在终端中,但它应该在我编写时工作./sequence < text.file。我在我的代码中找不到错误,此外,如果有人可以向我展示更好的方法,我将不胜感激。

text.file

whoami
cal 4 2020
echo The time is:
date

代码

#define MAX 10
#define LETTERS 256

/*Function definition to parse the command */
void parse(char *line, char **argv){


    char *token = line;
    char *extra;

  /* keep running until the end of the line  */

    while ((token = strtok_r(token, " \t\n", &extra)) != 0)
    {
        *argv++ = token;
        token = 0;
    }
  /* point the end of the argument to NULL*/

    *argv = 0;
}

/*Function definition of main()*/

int main(int argc, char *argv[]){

    char *arg[MAX],line[LETTERS];

    FILE *fp;

   /* Error checking for file opening */

    fp = fopen( argv, "r");
    if(fp == NULL){
        printf("ERROR NO input file \n");
        return 0;
    }
    pid_t pid;
    int status;

    /* Reading file line by line */

    while(fgets(line,LETTERS,fp)!= NULL){

        pid = fork();
    /*Errro checking for creation of child */

        if(pid < 0){
            printf("Fork child process failed!\n");
            exit(1);
        }
        else if(pid == 0){
            parse(line,arg);
            if(execvp(*arg,NULL) < 0){
                printf("Execvp failed!!\n");
                exit(1);
            }
        }
        else{
            wait(&status);       //Waiting for child process to finish.
        }
  }
  return 0;
}

终端

./sequence < text.file text.file

或者

./sequence text.file

结果

manrajnsinghdua
     April 2020
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

The time is:
Thu Apr 30 11:13:11 ACST 2020

标签: c

解决方案


你的电话fopen()不太正确,应该是fopen(argv[1], "r");,但只有在你确认之后argc >= 2


而不是做fopen(),听起来你只是想使用stdin.

如果要最小化代码更改,请更改:

    fp = fopen( argv, "r");

    fp = stdin;

推荐阅读