共有回帖数 0 个
-
这是一个用于查找关键字的程序,通过从keyword文档读取预存的32个关键字,然后通过strstr函数与origin文档的程序进行字符串的匹配,然后输出所在行的内容和出现的次数,但是现在遇到的问题是一个关键字的查找是可以完成的,然而两个甚至多个都会遇到根本没有进行匹配或者是?其他原因?以下是代码,以及我测试的截图,希望各位大神能够指点以下新手。
#include stdio.h
#include string.h
#include stdlib.h
#define MAX_LINE 300
#include windows.h
int main()
{
int i=0, j=0, flag=0,n=0;
int Line_key=0, Line_in=0;
char temp_key[MAX_LINE], temp_in[MAX_LINE];
char *string_key[MAX_LINE], *string_in[MAX_LINE];
FILE *in, *key, *out;
in = fopen("origin.txt","r");
key = fopen("keyword.txt","r");
out = fopen("out.txt","w");
if (in==NULL)
{
printf("Unable to open file in.txt!n");
exit(1);
}
if (key==NULL)
{
printf("Unable to open file key.txt!n");
exit(1);
}
if (out==NULL)
{
printf("Unable to open file out.txt!n");
exit(1);
}
for (Line_key=0; fgets(temp_key, MAX_LINE, key); Line_key++)//读取存放关键词,计算行
{
string_key[Line_key] = (char*)malloc(strlen(temp_key)+1);//开辟一个动态的内存区,将其地址转换成char*,放在指针数组中。
strcpy( string_key[Line_key],temp_key);
}
rewind(key);//文件指针重新指向流的开头
for (Line_in=0; fgets(temp_in, MAX_LINE, in); Line_in++)//读取需要查询的文件,并且计算其一共有多少行
{
string_in[Line_in] = (char*)malloc(strlen(temp_in)+1);
strcpy(string_in[Line_in], temp_in);
}
rewind(in);//文件指针重新指向流的开头
for (i=0; iLine_key; i++)//比较 匹配
{
color(2);
printf("NO.%d------Now,begin to check the 【%s】 in the source file-------n",i+1,string_key);color(16);
for (j=0; jLine_in; j++)
{
if(strstr(string_in[j], string_key))//将关键词指针数组中的字符串在源函数指针数组中的字符串进行查找,找到将返回指针位置。
{
printf("%6d: %s", j+1, string_in[j]);
n++;
fprintf(out, "%d: %s", j+1, string_in[j]);//向out文本文件中输入一个数据块
flag = 1;
}
} color(4);
printf("-------This keyword: 【%s】 appears %d time(s)--------n",string_key,n);
}color(16);
if (flag == 0)
{
printf("Unable to find the keyn");
}
for (i=0; iLine_key; i++)
free(string_key);//释放前面开辟的内存块,但并不改变string_key的值
for (j=0; jLine_in; j++)
free(string_in[j]);
fclose(key);
fclose(in);
fclose(out);
return 0;
}
void color(const unsigned short color1)
{
if(color1=0&&color1=15)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color1);
else
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}一个调色的函数,system(“color**”)是全部的貌似所以没用(这个不用管)



楼主 2015-06-18 23:57 回复
Copyright © 2010~2015 直线网 版权所有,All Rights Reserved.沪ICP备10039589号
意见反馈 |
关于直线 |
版权声明 |
会员须知