Blob


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