nextmatch

Find close matches to a line in a quote file, and print the next one.
git clone git://git.vgx.fr/nextmatch
Log | Files | Refs | Submodules

nextmatch.c (1108B)


      1 #include <stdbool.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 
      6 #include "levenshtein/levenshtein.h"
      7 
      8 #define MINSCORE 0.7
      9 
     10 void replace(char **dest, const char *src) {
     11   if (*dest)
     12     free(*dest);
     13   *dest = strdup(src);
     14 }
     15 
     16 int main(int argc, char *argv[]) {
     17   FILE *fp;
     18   char *line = NULL, *key = NULL, *next = NULL;
     19   double best_score = MINSCORE;
     20   bool get_next = false;
     21   size_t len = 0;
     22   ssize_t read;
     23 
     24   if(argc >= 3)
     25 	  fp = fopen(argv[2],"r");
     26   else
     27 	  fp = stdin;
     28 
     29   key = argv[1];
     30 
     31   if (fp == NULL || argc < 2 || key == NULL)
     32     exit(EXIT_FAILURE);
     33 
     34   while ((read = getline(&line, &len, fp)) != -1) {
     35     if (get_next) {
     36       replace(&next, line);
     37       get_next = false;
     38     }
     39 
     40     int dist = levenshtein(key, line) - 1; // -1 is for the trailing \n
     41 
     42     double score = (read - dist) / (double)read;
     43 
     44     if (score > best_score) {
     45 
     46       fprintf(stderr, "candidate (%lf = (%d-%d)/%d) : %s\n", score, read, dist,
     47               read, line);
     48       get_next = true;
     49     }
     50   }
     51 
     52   if (next) {
     53     printf("%s", next);
     54     free(next);
     55   }
     56 
     57   free(line);
     58   return EXIT_SUCCESS;
     59 }