简体   繁体   English

使用系统调用在C中实现grep

[英]Implementing grep in c using system calls

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h> 
#include <sys/stat.h>
#include <unistd.h>
#include<string.h>
#include <fcntl.h>

void match_pattern(char *argv[])
{
    int fd,r,j=0;
    char temp,line[100];
    if((fd=open(argv[2],O_RDONLY)) != -1)
    {
        while((r=read(fd,&temp,sizeof(char)))!= 0)
        {
            if(temp!='\n')
            {
                line[j]=temp;
                j++;
            }
            else
            {
                if(strstr(line,argv[1])!=NULL)
                    printf("%s\n",line);
                memset(line,0,sizeof(line));
                j=0;
            }

        }
    }   
}

main(int argc,char *argv[])
{
    struct stat stt;
    if(argc==3)
    {
        if(stat(argv[2],&stt)==0)
            match_pattern(argv);
        else 
        {
            perror("stat()");
            exit(1);
        }
    }
}

Contents of file: 文件内容:

arunds ghh
sdf
hi
hello dude
am arun

My output: 我的输出:

./mygrep arun file
arunds ghh
am arun

Am getting correct output 正在获得正确的输出

Content of file: 文件内容:

arun arundfdf arun
arunds ghh
sdf

My output: 我的输出:

./mygrep arun file
arun arundfdf arun �5
arunds ghh

I have no idea why some unwanted characters getting printed. 我不知道为什么要打印一些不需要的字符。

You never NULL-terminate your line buffer, so it will overflow after the end. 您永远不会以NULL终止line缓冲区,因此它将在结束后溢出。 Run the memset call also after you declared the line variable. 声明line变量后,还要运行memset调用。

You need to null-terminate the line but why do you read it one character at a time ? 您需要对line进行空终止,但是为什么每次只能读取一个字符呢? you could read whole lines with fgets() which will null-terminate the buffer for you: 您可以使用fgets()读取整行,这将为您的缓冲区以空值终止:

while (fgets(line, sizeof(line), file)) {
   if (strstr(line, argv[1])) {
    ...
   }
}

Also this will make sure you don't overflow the 100 bytes buffer you allocate. 此外,这将确保您不会溢出分配的100字节缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM