Random text generator using aspell words file.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

104 lines
2.3 KiB

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
/* 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 <num words>\n");
return 1;
}
int num;
if (argc == 1) {
num = 50;
} else {
num = atoi(argv[1]);
if (num <= 0) {
fprintf(stderr, "Usage: lipsum <num words>\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");
}