Reputation:
#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.
Upvotes: 0
Views: 18723
Reputation: 17312
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.
Upvotes: 0
Reputation: 33521
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.
Upvotes: 2