编程序,统计名为“p1.c"的文本文件中出现单词“if”的数目。当“if”的前面是字符“\n”或字符“空格”、后面是字符“空格”时,算1个单词。
#include"stdio.h" #include"string.h" main() { FILE*fp; int n=0; char ch,keyl[5]="\nif",key2[5]="if",str[5]; if((fp=fopen("p1.c","r"))==NULL) {printf("File not open!\n");exit(0);} while(!feof(fp)) {ch=fgetc(fp); if((ch=='\n'):{(ch=='')) { str[0]=ch; if(!feof(fp)) str[1]=fgetc(fp); else break; if(!feof(fp)) str[2]=fgetc(fp); else break; if(!feof(fp)) str[3]=fgetc(fp); else break; str[4]='\0'; if((strcmp(keyl,str)==0)¦¦(strcmp(key2,str)==0)) n++: else fseek(fp,-3L,1); } } fclose(fp); pri ntf("%d\n",n); }