I'm trying to match the whole string and not just part of it. For instance, if the needle is 2, I would like to match just the string 2 and not 20, 02, or 22 or anything related.
I'm using strstr as:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *file;
char l[BUFSIZ];
int linenumber = 1;
char term[6] = "2";
file = fopen(argv[1], "r");
if(file != NULL) {
while(fgets(l, sizeof(l), file)){
if(strstr(l, term) != NULL) {
printf("Search Term Found at %d!\n", linenumber);
}
++linenumber;
}
}
else {
perror(argv[1]);
}
fclose(file);
return 0;
}
Use strcmp instead of strstr or, for a better answer, define "anything related".
strstr is matching the string "2". If you don't want it to match things where 2 is combined with other things, you're going have to define exactly what "just the string 2" means. Is it 2 surrounded by whitespace?
I'm guessing what you really want to do is to tokenize the input (perhaps delimited on whitespace or something) and then check whether a token is the string "2". (In that case, use strtok and strcmp.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With