summaryrefslogtreecommitdiffstats
path: root/lib/unlink-recursive.c
blob: 434fdc791b324b7f53c3aab96d5df4562a89c6f7 (plain)
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
#include <common.h>
#include <libfile.h>
#include <errno.h>
#include <libbb.h>
#include <fs.h>

static char unlink_recursive_failedpath[PATH_MAX];

struct data {
	int error;
};

static int file_action(const char *filename, struct stat *statbuf,
			    void *userdata, int depth)
{
	struct data *data = userdata;
	int ret;

	ret = unlink(filename);
	if (ret) {
		strcpy(unlink_recursive_failedpath, filename);
		data->error = ret;
	}

	return ret ? 0 : 1;
}

static int dir_action(const char *dirname, struct stat *statbuf,
			    void *userdata, int depth)
{
	struct data *data = userdata;
	int ret;

	ret = rmdir(dirname);
	if (ret) {
		strcpy(unlink_recursive_failedpath, dirname);
		data->error = ret;
	}

	return ret ? 0 : 1;
}

int unlink_recursive(const char *path, char **failedpath)
{
	struct data data = {};
	int ret;

	if (failedpath)
		*failedpath = NULL;

	ret = recursive_action(path, ACTION_RECURSE | ACTION_DEPTHFIRST,
			file_action, dir_action, &data, 0);

	if (!ret && failedpath)
		*failedpath = unlink_recursive_failedpath;

	return ret ? 0 : -errno;
}