Xv6 with picoc & Linkage editor  v1.0
The project delineate mutual cohesion between c library, linkage editor ( linker), interpreter and operating system by porting the same on xv6 kernel
grep.c
00001 // Simple grep.  Only supports ^ . * $ operators.
00002 
00003 #include "types.h"
00004 #include "stat.h"
00005 #include "user.h"
00006 
00007 char buf[1024];
00008 int match(char*, char*);
00009 
00010 void
00011 grep(char *pattern, int fd)
00012 {
00013   int n, m;
00014   char *p, *q;
00015   
00016   m = 0;
00017   while((n = read(fd, buf+m, sizeof(buf)-m)) > 0){
00018     m += n;
00019     p = buf;
00020     while((q = strchr(p, '\n')) != 0){
00021       *q = 0;
00022       if(match(pattern, p)){
00023         *q = '\n';
00024         write(1, p, q+1 - p);
00025       }
00026       p = q+1;
00027     }
00028     if(p == buf)
00029       m = 0;
00030     if(m > 0){
00031       m -= p - buf;
00032       memmove(buf, p, m);
00033     }
00034   }
00035 }
00036 
00037 int
00038 main(int argc, char *argv[])
00039 {
00040   int fd, i;
00041   char *pattern;
00042   
00043   if(argc <= 1){
00044     printf( "usage: grep pattern [file ...]\n");
00045     exit(1);
00046   }
00047   pattern = argv[1];
00048   
00049   if(argc <= 2){
00050     grep(pattern, 0);
00051     exit(1);
00052   }
00053 
00054   for(i = 2; i < argc; i++){
00055     if((fd = open(argv[i], 0)) < 0){
00056       printf( "grep: cannot open %s\n", argv[i]);
00057       exit(1);
00058     }
00059     grep(pattern, fd);
00060     close(fd);
00061   }
00062   exit(1);
00063 }
00064 
00065 // Regexp matcher from Kernighan & Pike,
00066 // The Practice of Programming, Chapter 9.
00067 
00068 int matchhere(char*, char*);
00069 int matchstar(int, char*, char*);
00070 
00071 int
00072 match(char *re, char *text)
00073 {
00074   if(re[0] == '^')
00075     return matchhere(re+1, text);
00076   do{  // must look at empty string
00077     if(matchhere(re, text))
00078       return 1;
00079   }while(*text++ != '\0');
00080   return 0;
00081 }
00082 
00083 // matchhere: search for re at beginning of text
00084 int matchhere(char *re, char *text)
00085 {
00086   if(re[0] == '\0')
00087     return 1;
00088   if(re[1] == '*')
00089     return matchstar(re[0], re+2, text);
00090   if(re[0] == '$' && re[1] == '\0')
00091     return *text == '\0';
00092   if(*text!='\0' && (re[0]=='.' || re[0]==*text))
00093     return matchhere(re+1, text+1);
00094   return 0;
00095 }
00096 
00097 // matchstar: search for c*re at beginning of text
00098 int matchstar(int c, char *re, char *text)
00099 {
00100   do{  // a * matches zero or more instances
00101     if(matchhere(re, text))
00102       return 1;
00103   }while(*text!='\0' && (*text++==c || c=='.'));
00104   return 0;
00105 }
00106 
 All Data Structures