PatchworkOS  28a9544
A non-POSIX operating system.
Loading...
Searching...
No Matches
main.c
Go to the documentation of this file.
1#include <stdbool.h>
2#include <stdio.h>
3#include <string.h>
4
5int main(int argc, char** argv)
6{
7 if (argc < 2)
8 {
9 fprintf(stderr, "Usage: grep <pattern>\n");
10 return 1;
11 }
12
13 const char* pattern = argv[1];
14 char line[1024];
15
16 while (fgets(line, sizeof(line), stdin) != NULL)
17 {
18 if (strstr(line, pattern) == NULL)
19 {
20 continue;
21 }
22
23 bool inMatch = false;
24 for (char* p = line; *p != '\0'; p++)
25 {
26 if (strncmp(p, pattern, strlen(pattern)) == 0)
27 {
28 if (!inMatch)
29 {
30 printf("\033[31m");
31 inMatch = true;
32 }
33 printf("%.*s", (int)strlen(pattern), pattern);
34 p += strlen(pattern) - 1;
35 }
36 else
37 {
38 if (inMatch)
39 {
40 printf("\033[0m");
41 inMatch = false;
42 }
43 putchar(*p);
44 }
45 }
46 }
47
48 return 0;
49}
#define NULL
Pointer error value.
Definition NULL.h:23
int main(void)
Definition main.c:5
_PUBLIC char * fgets(char *_RESTRICT s, int n, FILE *_RESTRICT stream)
Definition fgets.c:5
_PUBLIC int putchar(int c)
Definition putchar.c:7
_PUBLIC int printf(const char *_RESTRICT format,...)
Definition printf.c:5
FILE * stderr
Definition std_streams.c:18
FILE * stdin
Definition std_streams.c:16
_PUBLIC int fprintf(FILE *_RESTRICT stream, const char *_RESTRICT format,...)
Definition fprintf.c:5
_PUBLIC char * strstr(const char *s1, const char *s2)
Definition strstr.c:3
_PUBLIC int strncmp(const char *s1, const char *s2, size_t n)
Definition strncmp.c:3
_PUBLIC size_t strlen(const char *s)
Definition strlen.c:3