char buf[1024];
void
grep(char *pattern, int fd)
{
int n, m;
char *p, *q;
m = 0;
while((n = read(fd, buf+m, sizeof(buf)-m-1)) > 0){
m += n;
buf[m] = '\0';
p = buf;
while((q = strchr(p, '\n')) != 0){
*q = 0;
if(match(pattern, p)){
*q = '\n';
write(1, p, q+1 - p);
}
p = q+1;
}
if(p == buf)
m = 0;
if(m > 0){
m -= p - buf;
memmove(buf, p, m);
}
}
}
I found a implementation of grep() in xv6 source code. I think there is a problem in the source code.
Consider the situation like there is a file containing a line more than 1024 character long and it contains the string unix (for example) after 1023th byte {abccee....unix...} and we are searching for that the string.
Now if we run the grep it will read the first 1023 character and as it doesn't find any newline character '\n' it discards the buffer by setting m = 0 then next time when it reads the rest of the line it finds the string unix and prints only from 1023th` byte {..unix...} but logically it should print the whole line but it simply discards the previous
portion of the line. So, I don't think it works correctly.
Note: I am considering the line starts with 0th, 1st, 2nd byte so on ...