I'm trying to selectively filter a text file by a string which is input to the standard input.
I would like to know why the following code does not work and how to fix it:
void get_filtered_list() {
FILE *f;
f = fopen("presentlist.txt", "r");
printf("Enter the city by which you want to select lines:\n");
char stringToFind[20];
fgets(stringToFind, sizeof(stringToFind), stdin);
char line[160];
while (!feof(f)) {
fgets(line, sizeof(line), f);
if (strstr(line, stringToFind) != NULL) {
printf("%s", line);
}
}
fclose(f);
}
This code above is trying to take a text file, opening that file, then reading the file line by line, and for each line executing the strstr()
function with the current line of the file as argument 1 as a string, and the given name of the city as argument 2 as a string.
However what I get as a result is the ENTIRE contents of the file printed (and the last line prints twice, though this is a separate issue and I know the fix to this part).
The C book I'm reading states that the strstr()
function is used to find a needle string in a haystack string, so it's the C equivalent of the C++ substr()
function.
strstr()
takes argument 1 as the haystack and argument 2 as the needle.
I first read in from the standard input into the needle, then line by line I check whether strstr()
returns NULL
or not (it should return NULL
if the needle is not found in the haystack) and if it returns something other than NULL
that means it found the substring in the string and it should only print the line THEN.
Instead it prints all of the lines in the file. Why?
If I switch it to f(strstr(line, stringToFind))
instead then it prints absolutely nothing.
Why?