c - 从文本文件中读取命令并依次执行
问题描述
所以我被告知要编写一个程序,其中程序应该读取并执行来自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
解决方案
你的电话fopen()
不太正确,应该是fopen(argv[1], "r");
,但只有在你确认之后argc >= 2
而不是做fopen()
,听起来你只是想使用stdin
.
如果要最小化代码更改,请更改:
fp = fopen( argv, "r");
至
fp = stdin;
推荐阅读
- php - 启用自定义模块存储,特别是 Magento 2 不起作用
- regex - 带有 csv 文件的 PowerShell 正则表达式
- python - 矩阵变换的嵌套列表
- c# - 使用 c# SmtpClient 的 Gmail SMTP 失败
- android - Firebase 数据库 - 为数据库中的用户设置规则
- html - 在 flexbox 的情况下,内联元素锚标记尊重顶部和底部的填充,为什么?
- python - 使用 OpenCV Python 创建新的相机源(Camera Driver Using Python)
- migration - 大型机迁移到 USS/Github
- java - 将数据插入 mysql 表时出现“java.lang.NullPointerException”错误
- angular - NGRX 效果无限循环