You are using fscanf()
to read the words out of your file, which is not the best way to do this. You should use getline(3)
or fgets(3)
to read each line of your file.
Additionally, this line:
const char *words[3]={cat,dog,snake,bee};
Needs to be able to hold 4 char*
pointers, not 3. You will also need to include quotes with these string literals. This is another way to do this:
const char *words[] = {"cat", "dog", "snake", "bee"};
Then to get the size of this array, just use sizeof(x) / sizeof(x[0])
.
Furthermore, in this code segment:
FILE *f;
const char *arr;
f=fopen("test.txt","r");
while(fscanf(f,"%s",arr)!EOF)
You are using fscanf()
on an uninitialized pointer, which leads to many problems. If you wish to use a pointer, you may need to dynamically allocate arr
on the heap with malloc(3)
. If you don't wish to do this, just declare a VLA, such as char arr[200]
. Also fscanf()
returns number of items scanned, so fscanf(f,"%s",arr)!=EOF
will have to be replaced with fscanf(f,"%s",arr)==1
, to ensure one word is being read at a time.
Note: You should also check if FILE *f
was opened correctly, as it can return NULL
on error.
I'm having trouble with the comparison. My thought was to save every word of the file into an array and compare each one with the words of the words array.
As others have mentioned to use strstr(3)
, another possible option is to use strtok(3)
to parse each word on the line, then use strcmp(3)
to compare words[i]
with the word parsed from the file. If words[]
becomes bigger in the future, I would suggest using binary search instead of linear search to compare the words. This will improve you search time from O(n) to O(logn).
Here is some (modified) code I wrote before which does something similar:
#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;
}