2 * Copyright 2002-2009, Haiku. All rights reserved.
3 * Distributed under the terms of the MIT License.
16 #include <FindDirectory.h>
21 choose_file(const char *path
)
23 struct dirent
*dirent
;
27 DIR *dir
= opendir(path
);
31 // count directory entries
33 while ((dirent
= readdir(dir
)) != NULL
) {
34 if (dirent
->d_name
[0] == '.')
44 // choose and open entry
46 chosen
= rand() % count
;
50 while ((dirent
= readdir(dir
)) != NULL
) {
51 if (dirent
->d_name
[0] == '.')
54 if (chosen
<= count
) {
59 strlcpy(name
, path
, sizeof(name
));
60 strlcat(name
, "/", sizeof(name
));
61 strlcat(name
, dirent
->d_name
, sizeof(name
));
63 fd
= open(name
, O_RDONLY
);
78 main(int argc
, char **argv
)
80 char path
[PATH_MAX
] = {'\0'};
81 const char *file
= path
;
88 srand(system_time() % INT_MAX
);
91 // if there are arguments, choose one randomly
92 file
= argv
[1 + (rand() % (argc
- 1))];
93 } else if (find_directory(B_SYSTEM_DATA_DIRECTORY
, -1, false, path
,
94 sizeof(path
)) == B_OK
) {
95 strlcat(path
, "/fortunes", sizeof(path
));
98 fd
= open(file
, O_RDONLY
, 0);
100 fprintf(stderr
, "Couldn't open %s: %s\n", file
, strerror(errno
));
104 if (fstat(fd
, &stat
) < 0) {
105 fprintf(stderr
, "stat() failed: %s\n", strerror(errno
));
109 if (S_ISDIR(stat
.st_mode
)) {
112 fd
= choose_file(file
);
114 fprintf(stderr
, "Could not find any fortune file.\n");
118 if (fstat(fd
, &stat
) < 0) {
119 fprintf(stderr
, "stat() failed: %s\n", strerror(errno
));
124 buffer
= malloc(stat
.st_size
+ 1);
125 if (buffer
== NULL
) {
126 fprintf(stderr
, "Not enough memory.\n");
130 if (read(fd
, buffer
, stat
.st_size
) < 0) {
131 fprintf(stderr
, "Could not read from fortune file: %s\n",
136 buffer
[stat
.st_size
] = '\0';
142 for (i
= 0; i
< stat
.st_size
- 2; i
++) {
143 if (!strncmp(buffer
+ i
, "\n%\n", 3)) {
150 printf("Out of cookies...\n");
154 count
= rand() % count
;
157 // find beginning & end
158 for (i
= 0; i
< stat
.st_size
- 2; i
++) {
159 if (!strncmp(buffer
+ i
, "\n%\n", 3)) {
170 puts(buffer
+ start
);