要求编程建立一个文本文件,每个单词不包括空格及跨行,单词由字符序列构成且区分大小写,完成以下功能:统计给定单词在文本文件中出现的总次数、检索输出某单词在文本文件中首次出现的行号及位置。
代码如下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void creatfile(FILE* fp)
{
char ch[1024];
//输入文本内容,以#结束
printf("\nEnter the contents of this file. End with # in the beginning of a line:\n");
fgets(ch,1024,stdin);
while(ch[0]!='#')
{
//写入文件
fputs(ch,fp);
fgets(ch,1024,stdin);
}
}
void search(FILE* fp,char b[])
{
//a[50]存放当前单词
char ch,a[50];
//定义单词第一次出现的行和列
int first_row,first_col;
int index=0,row=1,col=0,count=0; //count为该单词出现的次数,col为该单词是此行的第几个,row为单词出现的行号
//文件指针没有达到末尾时
while(!feof(fp))
{
ch=fgetc(fp);
if(isalpha(ch))
{
a[index]=ch;
index++;
}
else if(ch==' ')
{
if(index!=0)
{
col++;
}
a[index]='\0';//表示字符串结束
index=0;
if(strcmp(a,b)==0)
{
count++;
if(count==1)
{
first_row=row;
first_col=col;
}
}
}
//当前字符为回车时
else if(ch=='\n')
{
a[index]='\0';
row++;
index=0;
col=0;
if(strcmp(a,b)==0)
{
count++;
if(count==1)
{
first_row=row;
first_col=col;
}
}
}}
printf("This word appears %d time(s) in total.\n",count);
if(cout>0)
{
printf("The word %s first appears in line:%d,column:%d",b,first_row,first_col);
}
}
int main()
{
char b[50];
FILE *fp;
fp=fopen("word_search.txt","w+");
creatfile(fp);
printf("\nEnter the word you want to search:\n");
scanf("%s",b);
rewind(fp);
search(fp,b);
//操作完毕,关闭文件
fclose(fp);
return 0;
}
总结一下我在写的时候以及交作业的时候遇到的问题:
1.在createfile()执行以后要使用rewind()函数,使文件指针重新回到文件起始位置。
2.在检测到当前字符为空格或回车时要令a[index]=’\0’,表示字符串的结束;