c - 查找单词出现在C中的文本文件中的次数
问题描述
我正在编写一个程序,它从标准输入中获取一个字符串,并读取一个文本文件以查看文本文件中是否存在匹配项。一切正常,除非您在文本文件的末尾添加一个空格,然后输出如下...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool stringsEqual(char* str1, char * str2){
if(strlen(str1)!= strlen(str2)){
return false;
}
int i = 0;
for(i = 0; i < strlen(str1); i ++){
if(str1[i] != str2[i]){
return false;
}
}
return true;
}
void main(){
char * readFileName = "read5.txt";
FILE *reader = fopen(readFileName,"r");
char * word;
word = (char*) calloc(50,sizeof(char)); //word can be max 20 letters.
printf("Please enter the word you are looking for: ");
scanf("%s",word);
char *line = "";
line = (char*) calloc(150,sizeof(char));
int count = 0;
char c ;
if(word){
if(reader){
while(!feof(reader)){
fscanf(reader,"%s",line);
printf("%s ----> %s\n",line,word);
if(stringsEqual(line,word)){
count++;
}
// strcpy(line,""); //Reset the value assigned to line
}
printf("Number of matches: %d\n",count);
}
else{
printf("File cannot be located or does not exist\n");
}
}
else{
printf("Your word cannot be processed\n");
}
}
文本文件如下...
apple banana orange raspberry
控制台的输出如下
Please enter the word you are looking for: raspberry
apple ----> raspberry
banana ----> raspberry
orange ----> raspberry
raspberry ----> raspberry
raspberry ----> raspberry
Number of matches: 2
附加信息: - 文本文件和编写 C 程序的文本编辑器的行结尾都是 LF。- 我尝试使用 fgets 和 fgetc,但 fscanf 是查看文本文件并逐字阅读的最佳方式。
解决方案
fscanf 成功返回参数列表中成功填充的项目数。
因此,您可能需要检查 fscanf 的返回值,在您的情况下应该为 1。
如果不是 1,则中断 while 循环。