您正在使用fscanf() 从文件中读取单词,这不是最好的方法。您应该使用getline(3) 或fgets(3) 来读取文件的每一行。
另外,这一行:
const char *words[3]={cat,dog,snake,bee};
需要能够容纳 4 个 char* 指针,而不是 3 个。您还需要在这些字符串文字中包含引号。这是另一种方法:
const char *words[] = {"cat", "dog", "snake", "bee"};
然后要获取这个数组的大小,只需使用sizeof(x) / sizeof(x[0])。
此外,在此代码段中:
FILE *f;
const char *arr;
f=fopen("test.txt","r");
while(fscanf(f,"%s",arr)!EOF)
您在未初始化的指针上使用fscanf(),这会导致很多问题。如果您希望使用指针,您可能需要使用malloc(3) 在堆上动态分配arr。如果您不想这样做,只需声明一个 VLA,例如 char arr[200]。此外,fscanf() 返回扫描的项目数,因此必须将 fscanf(f,"%s",arr)!=EOF 替换为 fscanf(f,"%s",arr)==1,以确保一次读取一个单词。
注意:您还应该检查FILE *f 是否正确打开,因为它可能会在错误时返回NULL。
我在比较时遇到了问题。我的想法是将文件的每个单词保存到一个数组中,并将每个单词与单词数组的单词进行比较。
正如其他人提到的使用strstr(3),另一种可能的选择是使用strtok(3) 解析行中的每个单词,然后使用strcmp(3) 将words[i] 与从文件中解析的单词进行比较。如果将来words[] 变得更大,我建议使用二分搜索而不是线性搜索来比较单词。这会将您的搜索时间从 O(n) 缩短到 O(logn)。
这是我之前写的一些(修改过的)代码,它做了类似的事情:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAYSIZE(x) (sizeof x / sizeof x[0])
int main(void) {
const char *words[] = {"cat", "dog", "snake", "bee"};
FILE *fptr;
char *line = NULL, *word = NULL;
const char *delim = " \n";
size_t len = 0, lineno = 0;
ssize_t read;
fptr = fopen("somewords.txt", "r");
if (fptr == NULL) {
fprintf(stderr, "Error reading file\n");
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fptr)) != -1) {
lineno++;
word = strtok(line, delim);
while (word != NULL) {
for (size_t i = 0; i < ARRAYSIZE(words); i++) {
if (strcmp(word, words[i]) == 0) {
printf("Found matched word: %s, Line number: %zu\n", word, lineno);
}
}
word = strtok(NULL, delim);
}
}
free(line);
fclose(fptr);
return 0;
}