【发布时间】:2012-11-13 07:23:39
【问题描述】:
我正在编写一个小型 c 程序来测试一些 Unix 命令。 我为用户提供他可以测试的选项,然后允许他输入他的选项。如果用户输入数字 2 作为他的选择,则应运行以下代码,该代码正在测试文件上的 grep 命令。但是代码有问题 当我进入“模式”时,它开始一个无限循环, 有什么帮助吗?!!我在 Unix 编程方面没有太多经验。 当我输入数字 2 作为我的选择时出现问题,这意味着它是在 case no.2
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(){
char pattern[50];
int userInput;
pid_t childPID;
char filename[50];
FILE *file;
printf("Enter a File name:");
scanf("%s",filename);
file = fopen(filename, "r");
do{
printf("Enter what u want to do with the file:\n");
printf("1.Compress the file.\n");
printf("2.Search for a pattern at the file\n");
printf("3.Read the file (display the file content at the terminal)\n");
printf("4.Eject the program\n");
scanf("%d",&userInput);
switch(userInput){
case 1:
if(childPID == 0){
execl("/bin/gzip","gzip",filename,NULL);
exit(1);
}
break;
case 2: childPID = fork();
if(childPID ==0){
printf("Enter the pattern you want to search about:");
scanf("%s",pattern);
execl("/bin/grep","grep",pattern,filename,NULL);
}
break;
}
}while(userInput != 4);
return 0;
}
【问题讨论】:
-
模式是如何定义的?它是否足以容纳您的示例模式字符串?
-
我认为你应该使用选项
-f.. 表示将第四个参数传递为"-f"然后filename -
@OlafDietsche ,这就是我定义模式 char pattern[50];
-
@Omkant 我试过了,但是当我编译时,它产生了这个错误: Ass.c: In function 'main': Ass.c:45:39: error: 'f' undeclared (first在此函数中使用)Ass.c:45:39:注意:每个未声明的标识符对于它出现的每个函数只报告一次
-
你怎么知道这是一个无限循环?究竟会发生什么?