Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <string.h>
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8. if (argc < 2) {
  9. fprintf(stderr, "Usage: fortune [-d] filename\n");
  10. exit(-1);
  11. }
  12. /* use calloc to make a 256 sized array for fortune */
  13. char c, delimiter, fortune[256];
  14. short lines = 0, i = 0, count = 0;
  15.  
  16. FILE *file;
  17.  
  18. if (strncmp(argv[1], "-d", 2) == 0) {
  19. file = fopen(argv[3], "r");
  20. delimiter = *argv[2];
  21. }
  22.  
  23. else {
  24. file = fopen(argv[1], "r");
  25. delimiter = '\n';
  26. }
  27.  
  28. if (file == NULL) {
  29. fprintf(stderr, "file doesn't exist\n");
  30. exit(-1);
  31. }
  32.  
  33. while ((c = getc(file)) != EOF) {
  34. if (strncmp(&c, &delimiter, 1) == 0)
  35. lines++;
  36. }
  37.  
  38. rewind(file);
  39. i = rand() % lines;
  40.  
  41. while (fgets(fortune, sizeof(fortune), file) != NULL) {
  42. if (count == i) {
  43. /* if fortune exceends 256 add another 256 here ? */
  44. fortune[strlen(fortune) - 2] = '\0';
  45. printf("%s\n", fortune);
  46.  
  47. break;
  48. }
  49.  
  50. else
  51. count++;
  52. }
  53.  
  54. fclose(file);
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement