1. 程式人生 > >統計檔案中有多少個單詞&c語言實現

統計檔案中有多少個單詞&c語言實現

假設檔案中的單詞都是字母的組合,且單詞間用空格或者“."區分。實驗環境: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;	
} 

歡迎留言交流