假设文件中的单词都是字母的组合,且单词间用空格或者“."区分。
实验环境:Dev-C++
#include<stdio.h>
#include<stdlib.h>int main(){FILE *fp;int i;int fr;long fsize;int word=0;int sum=0;char filename[20];char *buffer;printf("要检查的文件:");scanf("%s",filename);fp=fopen(filename,"rb");if(!fp){perror("fp:");exit(0);}fseek(fp,0,SEEK_END);/*int fseek(FILE*stream,long offset,int fromwhere);参数:stream:FILE类型指针;offset 整数类型参数;fromwhere:文件头0(SEEK_SET),当前位置1(SEEK_CUR), 文件尾2(SEEK_END) ;取值0-2; 功能:设置文件指针stream的位置返回:成功:stream将指向以fromwhere为基准,偏移offset个字节的位置,函数返回0失败:不改变stream的指向的位置,函数返回一个非0值 */fsize=ftell(fp);/*long ftell(FILE *stream);功能:返回文件位置指针当前位置相对于文件首的偏移字节数 */ rewind(fp);/*void rewind(FILE *stream);功能:将文件位置指针重新指向文件开头 */ buffer=(char*)malloc((1+fsize)*sizeof(char));/*extern void *malloc(unsigned int num_bytes);头文件:#include<stdlin.h>或者#include<malloc.h>功能:向系统申请分配一个长度为num_butes个字节的内存块 */ if(!buffer){perror("mallocc:");exit(0);}fr=fread(buffer,1,fsize,fp);/*size_t fread(void *buffer,size_t size,size_t count,FILE *stream);功能:从文件流中读数据,最多读count项,每个项size个字节返回:成功:返回实际读取到的项个数失败:返回0 size_t fwrite(const void*buffer,size_t size,size_t count,FILE *stream);功能:向指定的文件写数据,写count项,每项size个字节返回:成功:返回实际写入的数据块数目该函数以二进制形式对文件进行操作,不局限与文本文件 */ if(fr==0){perror("fread:");exit(0);}buffer[fsize]='\0';for(i=0;i<fsize;i++){if(buffer[i]==' '||buffer[i]=='.')word=0;else if(word==0){word=1;sum++;}}printf("该文件中共有%d个单词\n",sum);return 0;
}
欢迎留言交流