您正在使用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;
}
使用'的strstr()',那將是很容易 –
我該使用怎樣的strstr完全相同()?我的意思是在打開我的文件和上面使用fscanf之後? – frog
'系統(「grep ...」)'...(鴨子和跑步......嘿,這是狂歡節......) – DevSolar