/* * main.c - Main entry point for neogrep * $author: Buckwheat of Neo-Sekai Club * $creation-date: 2026/02/28 * $version: 1.0.0 * */ #include #include #include #include #include #include #include #define NEWLINE '\n' #define NULTERM '\0' /* Function Declarations */ static int err_msg(const char*); static int substr_check(char*, const char*, int, int, int); /* Function Definitions */ static int err_msg(const char* msg) { printf("ERROR: %s\n", msg); return 1; } static int substr_check(char* data, const char* substr, int start, int len, int line) { int newlen = len + 1; char* str = (char*)malloc(sizeof(char) * newlen); if (!str) return -1; for (int index = 0; index < newlen; index++) if (index == len) str[index] = NULTERM; else str[index] = data[index + start]; if (strstr(str, substr)) printf("\033[1;31mLine %d: \033[4;32m%s\033[0m", line, str); free(str); return 0; } int main(int argc, char** argv) { if (argc > 3 || argc < 3) return err_msg("Insufficient arg count\nUsage: ng "); struct stat file_info; char* file_map; int char_count = 0; int file_size = 0; int line_count = 0; int src_file = -1; const char* substr = argv[2]; const char* src_name = argv[1]; src_file = open(src_name, O_RDONLY, 0); if (src_file == -1) return err_msg("Could not open input file"); fstat(src_file, &file_info); file_size = file_info.st_size; file_map = (char*)mmap(NULL, file_size, PROT_READ, MAP_SHARED, src_file, 0); if (file_map == MAP_FAILED) { close(src_file); return err_msg("mmap failed"); } for (int index = 0; index < file_size; index++) { char current = file_map[index]; if (current == NEWLINE) { line_count++; char_count = substr_check(file_map, substr, index - char_count, char_count + 1, line_count); } else char_count++; if (char_count == -1) return err_msg("Failed to malloc"); } if (munmap(file_map, file_size) == -1) return err_msg("munmap failed"); return 0; }