grep.c 1.94 KB
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>

#include "regex.h"

const char *ANSI_RESET_COLOR = "\033[39m\033[49m";
const char *ANSI_COLOR_PATTERN = "\033[38;2;%d;%d;%dm";

void search_file(char *regex, char *filename) {
    FILE* f = fopen(filename, "r");
    if (!f) {
        fprintf(stderr, "File %s does not exist!\n", filename);
        exit(2);
    }

    struct stat fstats;

    int result = fstat(fileno(f), &fstats);
    if (result) {
        fprintf(stderr, "Could not find the size of the file %s\n", filename);
        exit(2);
    }

    size_t file_length = fstats.st_size;

    char *contents = malloc((file_length + 1) * sizeof(char));
    fread(contents, file_length, sizeof(char), f);
    contents[file_length] = '\0';

     char *brkt;
     for (char *line = strtok_r(contents, "\n", &brkt); line; line = strtok_r(NULL, "\n", &brkt)) {
         if (!line) {
             puts("\n");
         }
         else {
             range_t *result = regexp_match(regex, line);
             if (result) {
                 char *to_print = calloc(strlen(line) + 1 + (strlen(ANSI_COLOR_PATTERN) + 3) + strlen(ANSI_RESET_COLOR), sizeof(char));
                 strncpy(to_print, line, result->start);
                 snprintf(to_print + result->start, strlen(ANSI_COLOR_PATTERN) + 3, ANSI_COLOR_PATTERN, 0, 128, 0);
                 strncat(to_print, line + result->start, result->end - result->start);
                 strcat(to_print, ANSI_RESET_COLOR);
                 strcat(to_print, line + result->end);
                 printf("%s\n", to_print);
             }
             free(result);
         }
     }
     free(contents);
     fclose(f);
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        fprintf(stderr, "USAGE: %s <regexp> filepaths...\n", argv[0]);
        exit(1);
    }

    char *regex = argv[1];
    for (size_t i = 2; i < argc; i++) {
        search_file(regex, argv[i]);
    }
}