summaryrefslogtreecommitdiff
path: root/userspace/grep.c
diff options
context:
space:
mode:
Diffstat (limited to 'userspace/grep.c')
-rw-r--r--userspace/grep.c67
1 files changed, 61 insertions, 6 deletions
diff --git a/userspace/grep.c b/userspace/grep.c
index 68d5b7a..058f1f8 100644
--- a/userspace/grep.c
+++ b/userspace/grep.c
@@ -1,18 +1,73 @@
#include <stdio.h>
#include <stdlib.h>
+// https://www.programmingsimplified.com/c/source-code/c-program-insert-substring-into-string
+//
+char *substring(char *string, int position, int length)
+{
+ char *pointer;
+ int c;
+
+ pointer = malloc(length+1);
+
+ if( pointer == NULL )
+ exit(EXIT_FAILURE);
+
+ for( c = 0 ; c < length ; c++ )
+ *(pointer+c) = *((string+position-1)+c);
+
+ *(pointer+c) = '\0';
+
+ return pointer;
+}
+
+
+void insert_substring(char *a, char *b, int position)
+{
+ char *f, *e;
+ int length;
+
+ length = strlen(a);
+
+ f = substring(a, 1, position - 1 );
+ e = substring(a, position, length-position+1);
+
+ strcpy(a, "");
+ strcat(a, f);
+ free(f);
+ strcat(a, b);
+ strcat(a, e);
+ free(e);
+}
+
int main(int argc, char **argv)
{
+ char col_start[]="\033[31;40m";
+ char col_end[]="\033[37;40m";
+
FILE *in=stdin;
FILE *out=stdout;
- while(1)
+ int i=1;
+ while(!feof(in))
{
- char buf[2];
- int l=fread(buf,1,1,in);
- if(l==0)break;
- buf[l]=0;
- fwrite(buf,1,l,out);
+ char buf[256];
+ char buf2[255];
+ fgets(buf,255,in);
+
+ char *pos=strstr(buf,argv[1]);
+ if(pos)
+ {
+ int p=pos-buf+1;
+ int l=strlen(argv[1])+strlen(col_start);
+
+ insert_substring(buf,col_start,p);
+ insert_substring(buf,col_end,p+l);
+
+ printf("%s",buf);
+ }
+
+ i++;
}
return EXIT_SUCCESS;