c实现数据字典批量替换文本内容

Posted: 2010年3月7日星期日
最近工作中需要大量替换log日志中的IP地址,使之显示ip对应的地区信息,于是用C写了个程序实现上述功能。
具体代码如下:

#include <stdio.h>
#include <stdlib.h>
#define __USE_GNU //为使用strcasestr函数添加
#include <string.h>

void str_replace(char *buf, const char *pre, const char *aft)
{
char *p;
//不区分大小写
p = strcasestr(buf, pre);
if (p){
char *p_2 = p + strlen(pre);
str_replace(p_2, pre, aft);
memmove(p + strlen(aft), p_2, strlen(p_2)+1);
memcpy(p, aft, strlen(aft));
}
}

int main(int argc, char *argv[])
{
FILE *fp1, *fp2;
char buf1[1024] = {0},
buf2[1024] = {0},
id[20] = {0},
name[32] = {0};

if (argc != 3) {
printf("%s \n", argv[0]);
exit(-1);
}

fp1 = fopen(argv[1], "r");
if (fp1 == NULL) {
printf("Open file %s FAILE!", argv[1]);
exit(-1);
}

fp2 = fopen(argv[2], "r");
if (fp2 == NULL) {
printf("Open file %s FAILE!", argv[2]);
exit(-1);
}

while (fgets(buf1, sizeof(buf1), fp1)) {
fseek(fp2, 0, SEEK_SET);
while (fgets(buf2, sizeof(buf2), fp2)) {
sscanf(buf2, "%s %s", id, name);
str_replace(buf1, id, name);
}
printf("%s", buf1);
}

fclose(fp1);
fclose(fp2);

return 0;
}

编译:
gcc -o replace replace.c

使用:
./replace apache.log ip.txt
其中apahce.log文件可以为任何格式的文本文件,ip.txt文件具体格式如下所示:

1.1.1.1 北京电信
2.2.2.2 天津联通
3.3.3.3 广州移动

第一列为IP地址,第二列为ip地址对应的地区信息。
该工具同样适用于其它的类似替换,代码中已做了不区分大小写处理。