diff options
author | rsc <devnull@localhost> | 2004-03-02 16:55:27 +0000 |
---|---|---|
committer | rsc <devnull@localhost> | 2004-03-02 16:55:27 +0000 |
commit | 6e2cec77b292cc2285e369ec01faa877ea91dbdd (patch) | |
tree | 8c4b9b9481f3838ee6c25b855d9e049435dbe1bc /src/cmd/fortune.c | |
parent | 34ca7ee3bff4fca54164345f20a16a1958bddcc2 (diff) | |
download | plan9port-6e2cec77b292cc2285e369ec01faa877ea91dbdd.tar.gz plan9port-6e2cec77b292cc2285e369ec01faa877ea91dbdd.tar.bz2 plan9port-6e2cec77b292cc2285e369ec01faa877ea91dbdd.zip |
missing programs
Diffstat (limited to 'src/cmd/fortune.c')
-rw-r--r-- | src/cmd/fortune.c | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/src/cmd/fortune.c b/src/cmd/fortune.c new file mode 100644 index 00000000..f3acfca2 --- /dev/null +++ b/src/cmd/fortune.c @@ -0,0 +1,90 @@ +#include <u.h> +#include <libc.h> +#include <bio.h> + +#define index findex +char choice[2048]; +char index[] = "/sys/games/lib/fortunes.index"; +char fortunes[] = "/sys/games/lib/fortunes"; + +#define lrand rand + +void +main(int argc, char *argv[]) +{ + int i; + long offs; + uchar off[4]; + int ix, nix; + int newindex, oldindex; + char *p; + Dir *fbuf, *ixbuf; + Biobuf *f, g; + + newindex = 0; + oldindex = 0; + ix = offs = 0; + if((f=Bopen(argc>1?argv[1]:fortunes, OREAD)) == 0){ + print("Misfortune!\n"); + exits("misfortune"); + } + ixbuf = nil; + if(argc == 1){ + ix = open(index, OREAD); + if(ix>=0){ + oldindex = 1; + ixbuf = dirfstat(ix); + fbuf = dirfstat(Bfildes(f)); + if(ixbuf == nil || fbuf == nil){ + print("Misfortune?\n"); + exits("misfortune"); + } + if(fbuf->mtime > ixbuf->mtime){ + nix = create(index, OWRITE, 0666); + if(nix >= 0){ + close(ix); + ix = nix; + newindex = 1; + oldindex = 0; + } + } + }else{ + ix = create(index, OWRITE, 0666); + if(ix >= 0) + newindex = 1; + } + } + if(oldindex){ + seek(ix, lrand()%(ixbuf->length/sizeof(offs))*sizeof(offs), 0); + read(ix, off, sizeof(off)); + Bseek(f, off[0]|(off[1]<<8)|(off[2]<<16)|(off[3]<<24), 0); + p = Brdline(f, '\n'); + if(p){ + p[Blinelen(f)-1] = 0; + strcpy(choice, p); + }else + strcpy(choice, "Misfortune!"); + }else{ + Binit(&g, ix, 1); + srand(getpid()); + for(i=1;;i++){ + if(newindex) + offs = Boffset(f); + p = Brdline(f, '\n'); + if(p == 0) + break; + p[Blinelen(f)-1] = 0; + if(newindex){ + off[0] = offs; + off[1] = offs>>8; + off[2] = offs>>16; + off[3] = offs>>24; + Bwrite(&g, off, sizeof(off)); + } + if(lrand()%i==0) + strcpy(choice, p); + } + } + print("%s\n", choice); + exits(0); +} |