Reputation: 37
I am writing a program in which I need to search for several full-written numbers. The searching part seems to work but for some reason the program is skipping several words. My code is as follows:
#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;
}
The mentioned file "numbers.txt" is as follows:
een
foo
drie
twee
acht
bla
zes
twaalf
elf
vier
The programs output:
een
drie
twee
acht
zes
vier
This means it is skipping "twaalf" and "elf". Why is it and how can I fix this?
Thanks on forehand.
Upvotes: 1
Views: 50
Reputation: 206607
int count = sizeof(myFile);
That seems to be a typo or a misunderstanding. sizeof(myFile)
evaluates to the number of bytes used by a pointer. You need to use:
int count = sizeof(words)/sizeof(words[0]);
The value of count
will be the number of words after that.
Upvotes: 5
Reputation: 3509
You are using count
and i
wrong.
The file has 10 lines, you set count
to this number 10, and use it then to access your number array also. You need to set count
to the number of elements in your array instead.
Upvotes: 0