Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int main(int argc, char *argv[])
- {
- if (argc < 2) {
- fprintf(stderr, "Usage: fortune [-d] filename\n");
- exit(-1);
- }
- /* use calloc to make a 256 sized array for fortune */
- char c, delimiter, fortune[256];
- short lines = 0, i = 0, count = 0;
- FILE *file;
- if (strncmp(argv[1], "-d", 2) == 0) {
- file = fopen(argv[3], "r");
- delimiter = *argv[2];
- }
- else {
- file = fopen(argv[1], "r");
- delimiter = '\n';
- }
- if (file == NULL) {
- fprintf(stderr, "file doesn't exist\n");
- exit(-1);
- }
- while ((c = getc(file)) != EOF) {
- if (strncmp(&c, &delimiter, 1) == 0)
- lines++;
- }
- rewind(file);
- i = rand() % lines;
- while (fgets(fortune, sizeof(fortune), file) != NULL) {
- if (count == i) {
- /* if fortune exceends 256 add another 256 here ? */
- fortune[strlen(fortune) - 2] = '\0';
- printf("%s\n", fortune);
- break;
- }
- else
- count++;
- }
- fclose(file);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement