效果:
chenqi@chenqi-laptop ~/MyPro/CFiles/highlighten $ ./highlight God input.txt
Six Dyas of Creation and the SabbathIn the beginning when God created the heavens and the earth, the earth was a formless void and darkness covered the faceof the deep, while a wind form God swept over the face of the waters. Then God said, "Let there be light"; and there was light. And God saw that the light was good; and God seperated the light form the darkness. God called the light Day, and the darkness he called Night. And there was evening and there was morning, the first day.
#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);
}