/* 通过关键字,从文件中提取有用的信息 */
int FindInfoFromFile(char *keyword, char *FilePath, char *OutString)
{
char *pattern;
int x, z, lno = 0, cflags = 0;
char ebuf[128], lbuf[256];
FILE *fp = NULL;
regex_t reg;
regmatch_t pm[10];
const size_t nmatch = 10;
pattern = keyword;
fp = fopen(FilePath, "r" );
if(fp == NULL)
{
fprintf(stderr,"%s[%d]:Cannot open %s\n", __FILE__, __LINE__, FilePath);
return -1;
};
z = regcomp(®, pattern, cflags);
if (z != 0)
{
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: pattern '%s' \n", ebuf, pattern);
fclose(fp);
fp = NULL;
return -1;
}
/* 逐行处理输入的数据 */
while (fgets (lbuf, sizeof (lbuf), fp))
{
++lno;
if ((z = (int)strlen(lbuf)) > 0 && lbuf[z - 1] == '\n')
lbuf[z - 1] = 0;
/*对每一行应用正则表达式进行匹配 */
z = regexec (®, lbuf, nmatch, pm, 0);
if (z == REG_NOMATCH)//没有匹配成功,continue
{
continue;
}
else if (z != 0)
{
regerror (z,®, ebuf, sizeof (ebuf));
fprintf (stderr, "%s: regcom('%s')\n", ebuf, lbuf);
fclose(fp);
fp = NULL;
return -2;
}
/* 输出处理结果 */
for (x = 0; x < nmatch && pm[x].rm_so != -1; ++x)
{
if (!x)
strcat(OutString, lbuf);
strcat(OutString, "\n");
}
}
/* 释放正则表达式 */
fclose(fp);
fp = NULL;
regfree (®);
return 0;
}