效果:less
chenqi@chenqi-laptop ~/MyPro/CFiles/highlighten $ ./highlight God input.txtspa
Six Dyas of Creation and the Sabbath#include <unistd.h> #include <stdio.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include <errno.h> #define MAX_LINE_LEN 256 /** * highlight: print out a line (str) to stdout with keyword highlightened * **/ static void highlight(const char *str, const char *keyword) { assert(str != NULL); assert(keyword != NULL); char *pos = NULL; const char *cur = str; int len_str = strlen(str); int len_keyword = strlen(keyword); while (1) { pos = strstr(cur, keyword); if (pos == NULL) { printf("%s", cur); break; } else /* find a substring starting at cur */ { while (cur < pos) putchar(*cur++); /* cur == pos */ printf("\033[40;31;1m"); while (cur < pos+len_keyword) putchar(*cur++); printf("\033[0m"); /* cur == pos+len_keyword */ } } } int main(int argc, char *argv[]) { assert(argc == 3); const char *keyword = argv[1]; const char *filepath = argv[2]; char buff[MAX_LINE_LEN]; FILE *infile = fopen(filepath, "r"); if (infile == NULL) { fprintf(stderr, "open file [%s] failed: %s \n", filepath, strerror(errno)); exit(EXIT_FAILURE); } while (1) { memset(buff, 0, MAX_LINE_LEN); char *str_ret = fgets(buff, MAX_LINE_LEN, infile); if (str_ret == NULL) { break; } else { highlight(buff, keyword); } } exit(EXIT_SUCCESS); }