C语言程序,在文件中查找指定字符串出现的次数,对文件操作实在没写过,看看怎么写

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILENAME_MAX 20

int StrCount(FILE *file,char *str);

void main()
{
char *filename,*spestr;
int num;
FILE *fp;
filename=(char *)malloc(FILENAME_MAX);
spestr=(char *)malloc(FILENAME_MAX);
printf("Input the filename:");
while(1)
{
scanf("%s",filename);
fp=fopen(filename,"r");
if(fp!=NULL)break;
printf("Can't open the file.");
}
printf("Input the special string:");
scanf("%s",spestr);
num=StrCount(fp,spestr);
fclose(fp);
printf("%d times of %s in %s.",num,spestr,filename);
}

int StrCount(FILE *file,char *str)
{
int i,length,count=0;
char ch,q,*temp;
char s[20];
q=*str;
length=strlen(str);
while(1)
{
while((ch=fgetc(file))!=EOF)
{
if(ch==q)
continue;
}
for(i=0;i<length;i++)
{
ch=fgetc(file);
s[i]=ch;
}
if(strcmp(str,s)==0)
count+=1;
if(ch==EOF)break;
}
return count;
}
运行出来貌似不行啊,strcount这个函数怎么改,对文件中的定位真是晕

第1个回答  2011-08-25
#include<iostream>
#include<conio.h>
#include<string>
#include<stdlib.h>
using namespace std;

int Count=0;

/*
*函数名:findNum
*作者:anglecloudy
*描述:如果存在则返回字符串所在的位置,否则返回0,暂不支持文本中存在多个相同的串
* 先用test.txt文本测试,所有的文本操作都是一样的,不管你怎么命名
*/
int findNum(char *str)
{
FILE *p;
if((p=fopen("test.txt","rb"))==NULL)
{
printf("\n打开文件失败\n");
return 0;
}
char buffer[0x1000]; //保存文件
memset(buffer,0,0x1000); //初始化缓存
size_t fileLen=fread(buffer,sizeof(char),0x1000,p); //得到文件内容,
int readLen=strlen(str);
int IsFind=0;

for(int i=0;i<fileLen;i++)
{
if(strncmp(buffer+i,str,readLen)==0)
{
IsFind=i;
}
}

fclose(p);
return IsFind;
}

int main(void)
{
char *str1="1234567";
int t1=0,t2=0;
if((t1=findNum(str1))==0)
{
printf("没有找到字符串%s\n请按任意键退出\n",str1);
return -1;
}
else
{
printf("字符串%s的位置在%d\n",str1,t1);
}
return 0;
}

我只是简单的改了一下你的字符串查找这个函数,其它的没写。主要是你的思想不对,对文件的操作一般先定义一个数组,把文件保存起来,然后再操作,多去上面问问,高手多,下班了。88
第2个回答  2011-08-24
int StrCount(FILE *file,char *str)
{
int i,length,count=0;
char ch,q,*temp;
char s[20];
q=*str;
length=strlen(str);
while(1)
{
while((ch=fgetc(file))!=EOF)
{
if(ch==q)
break;///
}
s[0]=ch;///
for(i=1;i<length;i++)
{
ch=fgetc(file);
s[i]=ch;
}
s[i]='\0';////strcmp比较是以'\0'结束的
if(strcmp(str,s)==0)
count+=1;
if(ch==EOF)break;
}
return count;
}本回答被提问者和网友采纳
第3个回答  2011-08-25
想了个效率比较低的:
1.fopen打开文件
2.fread每次读取一个字节和h(http的首字母)比较,成功了后再比较t,等等,如果都成功,说明匹配成功,然后将以后的字符读入到数组或文件中,同时用同样的方法检测.html字串。检测到.html字串就停止对数组或文件的写入。
如果有任何一个不匹配,重复步骤2(还得重新从比较h开始)
在怎么有效率也得遍历整个文件,我实在想不出什么别的更有效率的方法了。难道用哈希?散列?
相似回答