程序从文件中读取单词并在文件中计算它们的出现次数

我目前正在尝试创建一个程序来读取文件,找到每个唯一的单词并计算该单词在文件中出现的次数。 我目前要求用户输入一个单词并在文件中搜索该单词出现的次数。 但是我需要程序自己读取文件,而不是要求用户输入单个单词。

这就是我目前所拥有的:

#include  #include  int main(int argc, char const *argv[]) { int num =0; char word[2000]; char *string; FILE *in_file = fopen("words.txt", "r"); if (in_file == NULL) { printf("Error file missing\n"); exit(-1); } scanf("%s",word); printf("%s\n", word); while(!feof(in_file))//this loop searches the for the current word { fscanf(in_file,"%s",string); if(!strcmp(string,word))//if match found increment num num++; } printf("we found the word %s in the file %d times\n",word,num ); return 0; } 

我只是需要一些帮助来弄清楚如何阅读文件中的独特单词(它尚未检查的单词),尽管我的程序的任何其他建议将不胜感激。

如果只想打印文件中包含的每一行,则必须将已读取的字符串保存在给定的数据结构中。 例如,排序数组可以解决问题。 代码可能如下所示:

 #include  size_t numberOfLine = getNumberOfLine (file); char **previousStrings = allocArray (numberOfLine, maxStringSize); size_t i; for (i = 0; i < numberOfLine; i++) { char *currentString = readNextLine (file); if (!containString (previousStrings, currentString)) { printString (currentString); insertString (previousStrings, currentString); } } 

您可以使用二进制搜索以有效的方式对函数containStringinsertString进行编码。 请参阅此处了解更多信息。

您必须将代码拆分为函数(子例程)。

一个函数将读取文件并记录所有单词; 另一个会计算每个单词的出现次数。

 int main(int argc, char const *argv[]) { char *words[2000]; // Read the file; store all words in the list int number_of_words = ReadWords("words.txt", words, 2000); // Now count and print the number of occurrences for each word for (int i = 0; i < number_of_words; i++) { int n = CountOccurrences(words[i], "words.txt"); printf("we found the word %s in the file %d times\n", words[i], n); } // Deallocate dynamically allocated memory Cleanup(words, number_of_words); } 

注意mainfunction是如何相对较短的。 所有细节都在函数ReadWordsCountOccurrences

要实现从文件中读取所有单词:

 int ReadWords(const char *filename, char *words[], int max_number_of_words) { FILE *f = fopen(filename, "rt"); // checking for NULL is boring; i omit it int i; char temp[100]; // assuming the words cannot be too long for (i = 0; i < max_number_of_words; ++i) { // Read a word from the file if (fscanf(f, "%s", temp) != 1) break; // note: "!=1" checks for end-of-file; using feof for that is usually a bug // Allocate memory for the word, because temp is too temporary words[i] = strdup(temp); } fclose(f); // The result of this function is the number of words in the file return i; } 
 `#include  #include  int main(int argc, char*argv[]) { int num =0; char word[2000]; char string[30]; FILE *in_file = fopen(argv[1], "r"); if (in_file == NULL) { printf("Error file missing\n"); exit(-1); } scanf("%s",word); printf("%s\n", word); while(!feof(in_file))//this loop searches the for the current word { fscanf(in_file,"%s",string); if(!strcmp(string,word))//if match found increment num num++; } printf("we found the word %s in the file %d times\n",word,num ); return 0; }` if any suggestion plz..most welcome Blockquote