1

I've fiddled around with this code abit and still can't get it to work to my needs

I need to compare 'dict.txt' to 'output.txt'

so dict.txt is just a dictionary of thousands of words output.txt is decrypted strings in the structure such as:

"pkbld pjfqb kfqqk ebdfo"     
"diqol llrok rak"     
"zwpwx woaiw jwcan"     
"pvqbq xklfe obtxx s"     
"sense ofach ievem ent"    

as you can see one is valid, 'sense of achievement' I need to find out which lines are valid 'words' by comparing it to dict.txt

I've had a go at it by dismembering someone else's code to work with my task but I just can't get it right.

 int main() {
    FILE *fp;
    FILE *fp2;
    int line_num = 1;
    int find_result = 0;
    char temp[512];
    char str[512];

    fp = fopen("dict.txt","r");
    if(fp == NULL)
    {
        printf("Source File Could Not Be Found\n");
    }
    fp2 = fopen("output.txt","r");
    if(fp2 == NULL)
    {
        printf("Target File Could Not Be Found\n");
     }

    fgets(str, 512, fp2);

    while(fgets(temp, 512, fp) != NULL) {

        if((strstr(temp, str)) != 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 || fp2) {
        fclose(fp);
        fclose(fp2);
    }
    return(0);

    }

it works for finding only the first word in output.txt, other than that it doesn't.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • The code will find "sense" since that's a valid word. It should find "of" too, but not "achievement" since it has been split into three words. There's also the problem that [`fgets`](http://en.cppreference.com/w/c/io/fgets) reads a *line*, and you only read a single line from `output.txt`, not the full file. – Some programmer dude Oct 06 '17 at 09:12
  • `fgets(temp, 512, fp)` will only read 511 characters from output.txt – Gaurav Pathak Oct 06 '17 at 09:12
  • There are also other problems in the code, like you just ignoring a fatal error like not being able to open one of the file. Sure you print a message about it, but then you just continue as nothing happened, and will pass the null pointers to `fgets`. – Some programmer dude Oct 06 '17 at 09:13
  • You can use `fscanf` to automatically read text one word at a time, no complicated algorithm needed. [This post](https://stackoverflow.com/a/16401033/4808244) has a demonstration – Scott Forsythe Oct 20 '17 at 18:54

0 Answers0