aboutsummaryrefslogtreecommitdiff
path: root/cftw.c
blob: 8fb1d6701756701c95f62f0252781586640e4ce1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#define _POSIX_C_SOURCE 200809L

#include "cftw.h"
#include <dynstr.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

int cftw(const char *const dirpath, int (*const fn)(const char *,
    const struct stat *, void *), void *const user)
{
    int ret = -1;
    DIR *const d = opendir(dirpath);

    if (!d)
    {
        fprintf(stderr, "%s: opendir(2): %s\n", __func__, strerror(errno));
        goto end;
    }

    for (;;)
    {
        errno = 0;
        struct dirent *const de = readdir(d);

        if (errno)
        {
            fprintf(stderr, "%s: readdir(3): %s\n", __func__, strerror(errno));
            goto end;
        }
        else if (!de)
            break;

        const char *const path = de->d_name;

        if (!strcmp(path, ".") || !strcmp(path, ".."))
            continue;

        const char *const sep = dirpath[strlen(dirpath) - 1] == '/' ? "" : "/";
        struct stat sb;
        struct dynstr d;

        dynstr_init(&d);

        if (dynstr_append(&d, "%s%s%s", dirpath, sep, path))
        {
            fprintf(stderr, "%s: dynstr_append failed\n", __func__);
            return -1;
        }

        const int r = stat(d.str, &sb);

        if (r)
            fprintf(stderr, "%s: stat(2) %s: %s\n",
                __func__, path, strerror(errno));
        else if (S_ISDIR(sb.st_mode))
        {
            if ((ret = cftw(d.str, fn, user)))
                ;
            else if ((ret = fn(d.str, &sb, user)))
                ;
        }
        else if (S_ISREG(sb.st_mode))
            ret = fn(d.str, &sb, user);
        else
            fprintf(stderr, "%s: unexpected st_mode %ju\n",
                __func__, (uintmax_t)sb.st_mode);

        dynstr_free(&d);

        if (ret)
            goto end;
    }

    ret = 0;

end:

    if (d && closedir(d))
    {
        fprintf(stderr, "%s: closedir(2): %s\n", __func__, strerror(errno));
        ret = -1;
    }

    return ret;
}