在文本中查找字符串(参考,仅限ANSI ASCII)
程序代码:#include <stdio.h>
#include <stdlib.h>
#define stringSize(string) (sizeof(string) * sizeof(char))
void contains(char *, int, FILE *);
int main(void) {
FILE * fp;
char * fileName = "a.txt"; // 这里输入你的文本文件名
char str[] = "beautiful"; // 这里输入你想查找的字符串
if((fp = fopen(fileName, "rb")) == 0) {
printf("Can't open %s, program will to exit.", fileName);
exit(1);
}
contains(str, stringSize(str), fp);
fclose(fp);
return 0;
}
void contains(char * string, int stringSize, FILE * fp) {
int i = 0, j, end;
char * part = (char *)calloc(stringSize, sizeof(char));
fseek(fp, 0L, SEEK_END);
end = ftell(fp) - stringSize + 2;
while(i < end) {
j = 0;
fseek(fp, (long)i++, SEEK_SET);
fgets(part, stringSize, fp);
while(*part) {
if(*string == *part) {
j++;
string++;
part++;
continue;
}
break;
}
if(j == stringSize - 1) {
printf("OK\n");
break;
} else {
string -= j;
part -= j;
}
}
free(part);
}输出OK则代表对应文本中包含该字符串,无任何输出则表示不包含该字符串。注意:以换行结尾不能匹配,如
char str[] = "beautiful";
a.txt
//:start
1111111beau
tiful&&&&&!!
@@@@@@@@@@@
##########
//:end
第一行的最后4个字符beau和第二行的tiful可以组合成beautiful但在这个程序中不能匹配,如果你需要小改一下代码即可。

[ 本帖最后由 lz1091914999 于 2011-5-18 20:30 编辑 ]







