#include #include #include #include #define BUFSIZE 1024 char wordBuff[BUFSIZE]; char swipeBuff[BUFSIZE]; // fgets, but without the newline. char *fgetst(char *restrict s, int size, FILE *restrict stream) { char *r = fgets(s, size, stream); if (r) { char * sp = s; for(; sp[0] != '\0'; sp++) { if (sp[0] == '\n') { sp[0] = '\0'; } } } return r; } bool charcmp(char a, char b) { return tolower(a) == tolower(b); } bool swipeCompare(char *swipe, char *word) { if (! charcmp(swipe[0], word[0])) { return false; } char *swipeP = swipe; char *wordP = word; wordP++; bool lastMatch = false; for(swipeP++; swipeP[0]; swipeP++) { lastMatch = false; while (charcmp(swipeP[0], wordP[0])) { wordP++; lastMatch = true; } } if (wordP[0] == '\0' && lastMatch) { return true; } return false; } void query(FILE *wordFile, char *swipe, int n) { // TODO: UTF-8 len checking? if (swipe[0] == '\0' || swipe[1] == '\0') return; fseek(wordFile, 0, SEEK_SET); int found = 0; while (found < n && fgetst(wordBuff, BUFSIZE, wordFile)) { if (swipeCompare(swipe, wordBuff)) { if (found > 0) printf("\t"); printf("%s", wordBuff); found++; } } } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: swipeGuess words.txt [n]"); exit(1); } int n = 1; if (argc >= 3) { n = atoi(argv[2]); } FILE *wordFile = fopen(argv[1], "r"); while (fgetst(swipeBuff, BUFSIZE, stdin)) { query(wordFile, swipeBuff, n); printf("\n"); fflush(stdout); } fclose(wordFile); }