#include #include #include #include /* Read a line from a file into a newly created buffer */ int readline(FILE* in, char **out) { int size_of_buffer = 20; char *buffer = calloc(size_of_buffer, sizeof(char)); char character; int count = 0; while (true) { character = fgetc(in); if (character == EOF) { buffer[count] = '\0'; *out = buffer; return EOF; } if (character == '\n') { buffer[count] = '\0'; *out = buffer; return 0; } else { if (count == (size_of_buffer - 3)) { buffer = reallocarray(buffer, (size_of_buffer *= 2), sizeof(char)); if (!buffer) { return 1; } } buffer[count] = character; count++; } } } char **read_word_file(FILE *words, int *num_ret) { rewind(words); int listlen = 10; char **wordlist = calloc(listlen, sizeof(char *)); int no; for (no = 0; true; no++) { if (no == listlen) { listlen += 1; wordlist = reallocarray(wordlist, listlen, sizeof(char*)); char *nextword; int er = readline(words, &nextword); if (er == EOF) { break; } wordlist[no] = nextword; } } *num_ret = no; return wordlist; } int main (int argc, char **argv) { if (argc > 2) { fprintf(stderr, "Usage: lipsum \n"); return 1; } int num; if (argc == 1) { num = 50; } else { num = atoi(argv[1]); if (num <= 0) { fprintf(stderr, "Usage: lipsum \n"); return 1; } } unsigned int rand_seed = time(NULL); int len; FILE *words = fopen("/usr/share/dict/words", "r"); if (!words) { words = fopen("/usr/dict/words", "r"); } if (!words) { fprintf(stderr, "No words file found\n"); return 1; } char **wordlist = read_word_file(words, &len); fclose(words); for (int i = 0; i < num; i++) { int index = rand_r(&rand_seed) % len; printf("%s ", wordlist[index]); } printf("\n"); }