1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#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 swipeCompare(char *swipe, char *word) {
if (swipe[0] != word[0]) return false;
char *swipeP = swipe;
char *wordP = word;
wordP++;
bool lastMatch = false;
for(swipeP++; swipeP[0]; swipeP++) {
lastMatch = false;
while (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);
}
|