如何用C语言从文件中统计相同的字母个数

来源:百度知道 编辑:UC知道 时间:2024/05/16 05:07:09
例如:在1.txt中有
n1
n5
n6
n8
n112
n11
......
个数不超过120个,如何用C语言读出文件中含有几个字母"n"?
printf("1.txt中共有%d个n");

#include <stdio.h>
#include <malloc.h>

int main(void){
int i,len,count;
FILE *ifp;
char *text,*str,*str1;
len=0;

ifp=fopen("1.txt","r");
if (ifp == NULL)
{
printf("error!");
return;
}
while((i=fgetc(ifp))!=EOF) {len=len+1;}
rewind(ifp);

text=(char *)malloc(sizeof(char)*len);
for(i=0;i<len;i++) {
text[i]=fgetc(ifp);
printf("%c",text[i]);
}
fclose(ifp);
str = text;
while(str1 = strchr(str,'n'))
{
count += 1;
str = str1 + 1;
}
printf("1.txt中共有%d个n",count);
getch();
return 0;
}