Init mime struct
[rmail.git] / src / utils / file_utils.c
blob226e0f601e244f6d0eeb221dd7e97b58605ca82e
1 #define _BSD_SOURCE
3 #include <stdio.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <dirent.h>
7 #include <errno.h>
8 #include <fcntl.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
13 /**
14 * file_type
16 * @param[in] file file name
18 * @retval 0 file is "regular", 1 otherwise, -1 on error
20 int file_type(const char *file)
22 int fd;
23 struct stat fsb;
25 if (!file)
26 return -1;
28 fd = open(file, O_RDONLY);
29 if (fd < 0) {
30 fprintf(stderr, "%s - fstat %s: %s\n",
31 __func__, file, strerror(errno));
32 return -1;
35 if (fstat(fd, &fsb)) {
36 fprintf(stderr, "%s - fstat %s: %s\n",
37 __func__, file, strerror(errno));
38 close(fd);
39 return -1;
42 if (!S_ISREG(fsb.st_mode)) {
43 close(fd);
44 return 1;
47 close(fd);
48 return 0;
51 int scan_dir(const char *path, void (*file_callback)(const char *))
53 int rc = 0;
54 DIR *dir;
55 struct dirent *de;
57 if (!path)
58 return -1;
60 dir = opendir(path);
61 if (!dir) {
62 fprintf(stderr, "%s - %s: %s\n", __func__, path, strerror(errno));
63 return -1;
66 do {
67 de = readdir(dir);
68 if (de) {
69 file_callback(de->d_name);
70 continue;
73 /* de is null on error or EOD */
74 if (errno) {
75 rc = -1;
76 fprintf(stderr, "%s - %s!\n", __func__, strerror(errno));
77 break;
79 } while (de);
81 closedir(dir);
83 return rc;
86 size_t dir_entries(const char *path)
88 DIR *dir;
89 struct dirent *de;
90 size_t count = 0;
92 if (!path)
93 return 0;
95 dir = opendir(path);
96 if (!dir) {
97 fprintf(stderr, "%s - %s: %s\n", __func__, path, strerror(errno));
98 return 0;
101 do {
102 de = readdir(dir);
103 if (de) {
104 if (file_type(de->d_name) == 0)
105 count++;
106 continue;
109 /* de is null on error or EOD */
110 if (errno) {
111 fprintf(stderr, "%s - %s!\n", __func__, strerror(errno));
112 break;
114 } while (de);
116 closedir(dir);
118 return count;