我正在编写一个程序,我需要在其中搜索几个完整的数字。搜索部分似乎有效,但由于某种原因,程序跳过了几个单词。 我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[]){
char temp[128];
char *words[] = {"een","twee","drie","vier","vijf","zes","zeven","acht",
"negen","tien","elf","twaalf","dertien","veertien",
"vijftien","zestien","zeventien","achttien",
"negentien","twintig"};
//Open the file
FILE *myFile;
myFile = fopen("numbers.txt","r");
int count = sizeof(myFile);
if (myFile == NULL){
printf("File not found\n");
}
else {
//Search the words
while(!feof(myFile)){
//Get the words
fgets(temp, sizeof(temp), myFile);
for (int i = 0; i < count; ++i){
if((strstr(temp, words[i])) != NULL) {
printf("%s\n", temp);
}
}
}
}
return 0;
}
提到的文件“numbers.txt”如下:
een
foo
drie
twee
acht
bla
zes
twaalf
elf
vier
程序输出:
een
drie
twee
acht
zes
vier
这意味着它正在跳过“twaalf”和“elf”。为什么会这样,我该如何解决?
感谢正手。
最佳答案
int count = sizeof(myFile);
这似乎是一个打字错误或误解。 sizeof(myFile)
计算指针使用的字节数。您需要使用:
int count = sizeof(words)/sizeof(words[0]);
count
的值将是之后的单词数。
关于c - 程序没有搜索整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839160/