Parent: [152d47] (diff)

Child: [ae8ff5] (diff)

Download this file

wipedir.cpp    100 lines (82 with data), 1.9 kB

 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
90
91
92
93
94
95
96
97
98
99
#ifndef lint
static char rcsid[] = "@(#$Id: wipedir.cpp,v 1.2 2005-04-06 10:20:11 dockes Exp $ (C) 2004 J.F.Dockes";
#endif
#ifndef TEST_WIPEDIR
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <string>
using namespace std;
#include "debuglog.h"
#include "pathut.h"
#include "wipedir.h"
int wipedir(const string& dir)
{
struct stat st;
int statret;
int ret = -1;
statret = stat(dir.c_str(), &st);
if (statret == -1) {
LOGERR(("wipedir: cant stat %s, errno %d\n", dir.c_str(), errno));
return -1;
}
if (!S_ISDIR(st.st_mode)) {
LOGERR(("wipedir: %s not a directory\n", dir.c_str()));
return -1;
}
if (access(dir.c_str(), R_OK|W_OK|X_OK) < 0) {
LOGERR(("wipedir: no write access to %s\n", dir.c_str()));
return -1;
}
DIR *d = opendir(dir.c_str());
if (d == 0) {
LOGERR(("wipedir: cant opendir %s, errno %d\n", dir.c_str(), errno));
return -1;
}
int remaining = 0;
struct dirent *ent;
while ((ent = readdir(d)) != 0) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
string fn = dir;
path_cat(fn, ent->d_name);
struct stat st;
int statret = stat(fn.c_str(), &st);
if (statret == -1) {
LOGERR(("wipedir: cant stat %s, errno %d\n", fn.c_str(), errno));
goto out;
}
if (S_ISDIR(st.st_mode)) {
remaining++;
} else {
if (unlink(fn.c_str()) < 0) {
LOGERR(("wipedir: cant unlink %s, errno %d\n",
fn.c_str(), errno));
goto out;
}
}
}
ret = remaining;
out:
if (d)
closedir(d);
return ret;
}
#else // FILEUT_TEST
#include <sys/stat.h>
#include "wipedir.h"
using namespace std;
int main(int argc, const char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: wipedir <dir>\n");
exit(1);
}
string dir = argv[1];
int cnt = wipedir(dir);
printf("wipedir returned %d\n", cnt);
exit(0);
}
#endif