#include #include #include #include #include #include /* TODO: sysexits.h */ #define PROGRAM_NAME "wordle" #define DEFAULT_DICTIONARY_FILENAME "/usr/share/" PROGRAM_NAME "/dictionary.txt" #define DEFAULT_SOLUTIONS_FILENAME "/usr/share/" PROGRAM_NAME "/solutions.txt" #define WORD_LENGTH 5 #define GUESSES 6 int dictionary_has(char *s, int fd){ char buf[WORD_LENGTH + 2]; if(lseek(fd, 0, SEEK_SET) != 0){ fprintf(stderr, "%s: Could not seek to the start of the" " dictionary (errno %d).\n", PROGRAM_NAME, errno ); close(fd); exit(1); } /* unused, but just in case */ buf[WORD_LENGTH + 1] = '\0'; if(read(fd, buf, WORD_LENGTH + 1) < WORD_LENGTH) return 1; } int strisuint(char *s){ while(*s != '\0') if(!isdigit(*(s++))) return 0; return 1; } void usage(char *name){ fprintf(stderr, "Usage: %s [index] (-d [dictionary file])" " (-s [solutions file])\n", name ); exit(1); } int main(int argc, char *argv[]){ int c; int dictionary_fd; size_t i; size_t index; size_t j; FILE *solutions_file; char word[WORD_LENGTH + 1]; /* arg parse */ if(argc < 2) usage(argv[0] != NULL ? argv[0] : PROGRAM_NAME); while((c = getopt(argc, argv, "d:hs:")) != -1) switch(c){ case 'd': dictionary_filename = optarg; break; case 's': solutions_filename = optarg; break; case 'h': usage(argv[0] != NULL ? argv[0] : PROGRAM_NAME); } if(!strisuint(argv[optind])){ fprintf(stderr, "%s: index must be a number.\n", argv[0] != NULL ? argv[0] : PROGRAM_NAME ); exit(1); } index = (size_t)atoi(argv[optind]); /* get word */ if((solutions_file = fopen(solutions_filename, "rb")) == NULL){ fprintf(stderr, "%s: %s: Error opening solutions file.\n", argv[0] != NULL ? argv[0] : PROGRAM_NAME, solutions_filename ); exit(1); } i = j = 0; while((c = getc(solutions_file)) != EOF) if(i == index){ if(j == WORD_LENGTH){ word[WORD_LENGTH] = '\0'; j = 0; break; }else word[j++] = c; }else i += c == '\n'; if(j != '\0'){ word[j] = '\0'; fprintf(stderr, "%s: %s: Word is too few characters.\n", argv[0] != NULL ? argv[0] : PROGRAM_NAME, word ); exit(1); } fclose(solutions_file); if(dictionary_fd = open(dictionary_filename, O_RDONLY) == NULL){ fprintf(stderr, "%s: %s: Error opening dictionary file.\n", argv[0] != NULL ? argv[0] : PROGRAM_NAME, dictionary_filename ); exit(1); } close(dictionary_fd); exit(0); }