I have an issue about searching in .txt file. Here is my code:
int Search_in_File(char *fname, char pass[]) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[20];
if((fp = fopen(fname, "r")) == NULL) {
return(-1);
}
while(fgets(temp, 20, fp) != NULL) {
if(strncmp(temp, pass, 6) == 0)
{
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
int main(void) {
char pass[20];
printf("Enter a password:\n");
scanf("%s", &pass);
Search_in_File("100000.txt", pass);
getchar();
return 0 ;
}
If i use strcmp()
, The program cannot find any matches. But if I use strncmp()
, I can get the results but I get all passwords which matches the first 6 characters. How can i get exact matches?