简体   繁体   中英

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. Run the memset call also after you declared the line variable.

You need to null-terminate the line but why do you read it one character at a time ? you could read whole lines with fgets() which will null-terminate the buffer for you:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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