统计文件中每个单词的个数--C语言实现

来源:互联网 发布:windows phone 百度云 编辑:程序博客网 时间:2024/05/22 05:07
#include <stdio.h>#include <stdlib.h>#include <string.h>//这个程序是再Linux环境下写的,用到了命令行参数 struct Word  //声明一个结构体,分别存储单词和对应单词的个数 {size_t time;char word[20];};void Copy(struct Word *array, FILE *read, const int length);void Count_for_word(struct Word *array, const int length);int main(int argc, char *argv[]){char word[20];int length = 0, ch;FILE *read;struct Word *array;if (argc < 2 || argc > 2){printf("usage: %s filename\n", argv[0]);exit(EXIT_FAILURE);}if ((read = fopen(argv[1], "r")) == NULL){printf("open file failure\n");exit(EXIT_FAILURE);}while (fscanf(read, "%s", &word) != EOF) //测试是否读到文件末尾 ++length;  //统计文本中单词的个数 rewind(read); //把文件指针置为文本开始的位置,并清除错位信息 array = malloc(sizeof(struct Word) * length);Copy(array, read, length);return 0;}void Copy(struct Word *array, FILE *read, const int length) //该函数的作用是把文本中的单词复制到数组中 {char ch, word[20];int i = 0, j;while (fscanf(read, "%s", &word) != EOF)  {strcpy(array[i].word, word);++i;  //移动数组的下标 }fclose(read);Count_for_word(array, length);}void Count_for_word(struct Word *array, const int length) //统计单词的个数 {int i, j;for (i = 0; i < length; i++){array[i].time = 1;for (j = i+1; j < length; j++){if (strcmp(array[i].word, array[j].word) == 0){++array[i].time; //如果遇到相同的单词,就把相应的结构体部分增加 1 strcpy(array[j].word, " "); //并把该单词置为空,应为已经读取到数组中了,所以这里改变的是数组的数据,不影响文本数据 }}}printf("the file have %d word\n\n", length);for (i = 0; i < length; i++)if (strcmp(array[i].word, " ") != 0)printf("%-5s occurrs  %-3d %s\n", array[i].word, array[i].time, ((array[i].time > 1) ? "times" : "time"));}

原创粉丝点击