1 /* 2 ** Copyright 2002-2004, The OpenBeOS Team. All rights reserved. 3 ** Distributed under the terms of the OpenBeOS License. 4 */ 5 6 #include <unistd.h> 7 #include <string.h> 8 #include <stdlib.h> 9 #include <stdio.h> 10 #include <fcntl.h> 11 #include <sys/stat.h> 12 #include <errno.h> 13 14 #include <OS.h> 15 16 #define FORTUNES "/etc/fortunes" 17 18 int 19 main(void) 20 { 21 int fd; 22 int rc; 23 char *buf; 24 unsigned i; 25 unsigned found; 26 struct stat stat; 27 28 fd = open(FORTUNES, O_RDONLY, 0); 29 if (fd < 0) { 30 printf("Couldn't open %s: %s\n", FORTUNES, strerror(errno)); 31 return -1; 32 } 33 34 rc = fstat(fd, &stat); 35 if (rc < 0) { 36 printf("stat() failed: %s\n", strerror(errno)); 37 return -1; 38 } 39 40 buf = malloc(stat.st_size + 1); 41 rc = read(fd, buf, stat.st_size); 42 if (rc < 0) { 43 printf("Could not read from fortune file: %s\n", strerror(errno)); 44 return -1; 45 } 46 47 buf[stat.st_size] = 0; 48 close(fd); 49 50 found = 0; 51 for (i = 0; i < stat.st_size; i++) { 52 if (!strncmp(buf + i, "#@#", 3)) 53 found += 1; 54 } 55 56 if (found > 0) 57 found = 1 + ((system_time() + 3) % found); 58 else { 59 printf("Out of cookies...\n"); 60 return -1; 61 } 62 63 for (i = 0; i < stat.st_size; i++) { 64 if (!strncmp(buf + i, "#@#", 3)) 65 found -= 1; 66 67 if (found == 0) { 68 unsigned j; 69 70 for (j = i + 1; j < stat.st_size; j++) { 71 if (!strncmp(buf + j, "#@#", 3)) 72 buf[j] = 0; 73 } 74 75 printf("%s\n", buf + i + 3); 76 break; 77 } 78 } 79 80 return 0; 81 } 82