高亮关键词并且输出(Highlighten Keywords )

效果:

chenqi@chenqi-laptop ~/MyPro/CFiles/highlighten $ ./highlight God input.txt

Six Dyas of Creation and the Sabbath
In 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);
}



转载于:https://my.oschina.net/u/158589/blog/60411

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值