chiark / gitweb /
4a061837f29ca51dae5dd8519df035906a0eaaa3
[elogind.git] / src / basic / dirent-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright 2010-2012 Lennart Poettering
4 ***/
5
6 #include <fcntl.h>
7 #include <sys/stat.h>
8
9 #include "dirent-util.h"
10 #include "path-util.h"
11 #include "string-util.h"
12
13 int dirent_ensure_type(DIR *d, struct dirent *de) {
14         struct stat st;
15
16         assert(d);
17         assert(de);
18
19         if (de->d_type != DT_UNKNOWN)
20                 return 0;
21
22         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
23                 return -errno;
24
25         de->d_type =
26                 S_ISREG(st.st_mode)  ? DT_REG  :
27                 S_ISDIR(st.st_mode)  ? DT_DIR  :
28                 S_ISLNK(st.st_mode)  ? DT_LNK  :
29                 S_ISFIFO(st.st_mode) ? DT_FIFO :
30                 S_ISSOCK(st.st_mode) ? DT_SOCK :
31                 S_ISCHR(st.st_mode)  ? DT_CHR  :
32                 S_ISBLK(st.st_mode)  ? DT_BLK  :
33                                        DT_UNKNOWN;
34
35         return 0;
36 }
37
38 bool dirent_is_file(const struct dirent *de) {
39         assert(de);
40
41         if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
42                 return false;
43
44         if (hidden_or_backup_file(de->d_name))
45                 return false;
46
47         return true;
48 }
49
50 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
51         assert(de);
52
53         if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
54                 return false;
55
56         if (de->d_name[0] == '.')
57                 return false;
58
59         if (!suffix)
60                 return true;
61
62         return endswith(de->d_name, suffix);
63 }
64
65 struct dirent* readdir_no_dot(DIR *dirp) {
66         struct dirent* d;
67
68         for (;;) {
69                 d = readdir(dirp);
70                 if (d && dot_or_dot_dot(d->d_name))
71                         continue;
72                 return d;
73         }
74 }