0

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?

  • 2
    [fgets manual](https://linux.die.net/man/3/fgets): *If a newline is read, it is stored into the buffer*. Strip the trailing newline from `temp`. – kaylum Jan 22 '21 at 21:45
  • Does this answer your question? [strcmp on a line read with fgets](https://stackoverflow.com/questions/2404794/strcmp-on-a-line-read-with-fgets) – kaylum Jan 22 '21 at 21:48
  • @kaylum alright man, I solved it with `strtok()`. Thanks for help! – Mustafa Yılmaz Jan 22 '21 at 21:52
  • You should add a maximum width: `scanf("%19s", &pass);` Usiing `scanf` with an unconstrained `%s` is no better than `gets`. – William Pursell Jan 22 '21 at 21:53

1 Answers1

0

Bruteforce approach.

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int findInFile(FILE *fp, const char *str)
{
    void *data;
    long flength;
    int result = -1;

    fseek(fp, 0L, SEEK_END);
    flength = ftell(fp);
    fseek(fp, 0L, SEEK_SET);

    data = malloc(flength);
    if(data && fread(data, flength, 1, fp) == flength)
    {
        result = 0;
        char *pos = memmem(data, flength, str, strlen(str));
        if(pos)
        {
            printf("Match at %zu\n", pos - (char *)data);
        }
        else
        {
            printf("String not found\n");
        }
    }
    free(data);
    fseek(fp, 0L, SEEK_SET);
    return result;
}
0___________
  • 60,014
  • 4
  • 34
  • 74