#include #include #include #include #include char src_file[] = "/home/averhuls/twain/quotes"; main(argc, argv) int argc; char **argv; { int i, j, len, num_entries, index, blank_lines; struct stat stat_buf; char *buffer; char line[128]; int entry_index_array[200]; time_t tloc; FILE *fp; /* * Open the file containing the quotes. */ if ((fp = fopen(src_file, "r")) == (FILE *) 0) { char buf[40]; sprintf(buf, "can't open %s\n", src_file); perror(buf); exit(1); } /* * Get the size of the quotes file and allocate space for it. */ if (stat(src_file, &stat_buf) == -1) { perror("fstat"); exit(1); } buffer = (char *) malloc(stat_buf.st_size); /* * Find number of entries in src_file and build the * entry_index_array. */ i = 0; num_entries = 1; while (fgets(line, 128,fp)) { len = strlen(line); strncpy(&buffer[i], line, len); i += len; buffer[i-1] = 0; // terminate the line if (line[0] == '\n') { num_entries++; entry_index_array[num_entries] = i; } } fclose(fp); /* * If an output file name is specified, open it. */ if (argc > 1) { if ((fp = fopen(argv[1], "w+")) == (FILE *)0) { printf("can't open %s\n", argv[1]); perror(""); exit(1); } if (strcmp(argv[1], "/etc/motd") == 0) { blank_lines = 9; } else { blank_lines = 1; } } else { fp = stdout; blank_lines = 1; } /* * Find entry to generate. */ time(&tloc); srand(tloc); index = rand() % num_entries; /* * Index into buffer for the chosen (pseudo random) quote */ i = entry_index_array[index]; /* * Write output. */ for (j = 0; j < blank_lines; j++) { fputs("\n", fp); } /* write until we get to a blank line */ while (buffer[i] != '\0') { fputs(&buffer[i], fp); fputs("\n", fp); i += strlen(&buffer[i]) + 1; // skip past line terminator } fputs("\nMark Twain\n", fp); for (j = 0; j < blank_lines; j++) { fputs("\n", fp); } free(buffer); fclose(fp); }