Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c - Searching a string from a file

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
", line_num);
            printf("
%s
", temp);
            find_result++;
        }
        line_num++;
    }

    if(find_result == 0) {
        printf("
Sorry, couldn't find a match.
");
    }
    
    //Close the file if still open.
    if(fp) {
        fclose(fp);
    }
    return(0);
}

int main(void) {
char pass[20];
printf("Enter a password:
");
    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?

question from:https://stackoverflow.com/questions/65853162/searching-a-string-from-a-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", pos - (char *)data);
        }
        else
        {
            printf("String not found
");
        }
    }
    free(data);
    fseek(fp, 0L, SEEK_SET);
    return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...