我试图用C程序(仅用于学习)模拟UNIX的grep 模式。我写是给我一个运行时间错误的代码..使用UNIX的read()系统调用来查找用户给定的模式
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define MAXLENGTH 1000
char userBuf[MAXLENGTH];
int main (int argc, char *argv[])
{
int numOfBytes,fd,i;
if (argc != 2)
printf("Supply correct number of arguments.\n");
//exit(1);
fd =open("pattern.txt",O_RDWR);
if (fd == -1)
printf("File does not exist.\n");
//exit(1);
while ((numOfBytes = read(fd,userBuf,MAXLENGTH)) > 0)
;
printf("NumOfBytes = %d\n",numOfBytes);
for(i=0;userBuf[i] != '\0'; ++i)
{
if (strstr(userBuf,argv[1]))
printf("%s\n",userBuf);
}
}
的程序被无限打印时,含有图案行。我试过调试,但无法找出错误。请让我知道我错了,
感谢
*“我试过调试”*不是很清楚。你尝试了什么?遍历调试器中的代码?插入推测的'printf'来探究发生了什么? – dmckee
是的。非常好。 – Kelly