fortune.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. char choice[2048];
  5. char index[] = "/sys/games/lib/fortunes.index";
  6. char fortunes[] = "/sys/games/lib/fortunes";
  7. void
  8. main(int argc, char *argv[])
  9. {
  10. int i;
  11. long offs;
  12. uchar off[4];
  13. int ix, nix;
  14. int newindex, oldindex;
  15. char *p;
  16. Dir *fbuf, *ixbuf;
  17. Biobuf *f, g;
  18. newindex = 0;
  19. oldindex = 0;
  20. ix = offs = 0;
  21. if((f=Bopen(argc>1?argv[1]:fortunes, OREAD)) == 0){
  22. print("Misfortune!\n");
  23. exits("misfortune");
  24. }
  25. ixbuf = nil;
  26. if(argc == 1){
  27. ix = open(index, OREAD);
  28. if(ix>=0){
  29. oldindex = 1;
  30. ixbuf = dirfstat(ix);
  31. fbuf = dirfstat(Bfildes(f));
  32. if(ixbuf == nil || fbuf == nil){
  33. print("Misfortune?\n");
  34. exits("misfortune");
  35. }
  36. if(fbuf->mtime > ixbuf->mtime){
  37. nix = create(index, OWRITE, 0666);
  38. if(nix >= 0){
  39. close(ix);
  40. ix = nix;
  41. newindex = 1;
  42. oldindex = 0;
  43. }
  44. }
  45. }else{
  46. ix = create(index, OWRITE, 0666);
  47. if(ix >= 0)
  48. newindex = 1;
  49. }
  50. }
  51. if(oldindex){
  52. seek(ix, truerand()%(ixbuf->length/sizeof(offs))*sizeof(offs), 0);
  53. read(ix, off, sizeof(off));
  54. Bseek(f, off[0]|(off[1]<<8)|(off[2]<<16)|(off[3]<<24), 0);
  55. p = Brdline(f, '\n');
  56. if(p){
  57. p[Blinelen(f)-1] = 0;
  58. strcpy(choice, p);
  59. }else
  60. strcpy(choice, "Misfortune!");
  61. }else{
  62. Binit(&g, ix, 1);
  63. srand(truerand());
  64. for(i=1;;i++){
  65. if(newindex)
  66. offs = Boffset(f);
  67. p = Brdline(f, '\n');
  68. if(p == 0)
  69. break;
  70. p[Blinelen(f)-1] = 0;
  71. if(newindex){
  72. off[0] = offs;
  73. off[1] = offs>>8;
  74. off[2] = offs>>16;
  75. off[3] = offs>>24;
  76. Bwrite(&g, off, sizeof(off));
  77. }
  78. if(lrand()%i==0)
  79. strcpy(choice, p);
  80. }
  81. }
  82. print("%s\n", choice);
  83. exits(0);
  84. }