-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrmfiles.cc
109 lines (99 loc) · 2.53 KB
/
rmfiles.cc
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
100
101
102
103
104
105
106
107
108
109
/*
* Remove files from stdin, on file per line
* Directories are removed recursively
* Author: [email protected]
* Date: 11.01.2011
*/
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
int remove_directory(const char *path)
{
int r = -1;
size_t path_len = strlen(path);
DIR *d = opendir(path);
printf("Removing directory: %s\n",path);
if (d) {
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) {
int r2 = -1;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
size_t len = path_len + strlen(p->d_name) + 2;
char* filename = (char*)malloc(len);
if (filename) {
struct stat statbuf;
snprintf(filename, len, "%s/%s", path, p->d_name);
if (!stat(filename, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(filename);
else {
printf("Removing: %s\n",filename);
r2 = unlink(filename);
if (r2)
fprintf(stderr,"Error removing \"%s\"\n",filename);
}
}
free(filename);
}
r = r2;
}
closedir(d);
}
if (!r) r = rmdir(path);
return r;
} // remove_directory
/* --- main --- */
int main(int ac, char *av[])
{
if (ac==1) {
fprintf(stderr,"syntax: %s <base> [<fromfile>]\n",av[0]);
fprintf(stderr,"delete recursively sub-files and directories from base given in stdin\n");
fprintf(stderr,"Author: [email protected]\n");
fprintf(stderr,"Date: 11.01.2011\n");
exit(0);
}
char filename[FILENAME_MAX];
strcpy(filename, av[1]);
size_t lenbase = strlen(filename);
/* add a trailing / if needed */
if (filename[lenbase-1]!='/') {
filename[lenbase++] = '/';
filename[lenbase] = 0;
}
FILE* fin=stdin;
if (ac==3) {
fin = fopen(av[2],"r");
if (!fin) {
fprintf(stderr,"Cannot open file \"%s\"\n",av[2]);
return -1;
exit(-1);
}
}
while (fgets(filename+lenbase, sizeof(filename)-lenbase, fin)!=NULL) {
struct stat statbuf;
size_t len = strlen(filename);
int r = -1;
/* strip trailing CR, LF */
while (filename[len-1]==0x0D || filename[len-1]==0x0A)
filename[--len] = 0;
if (len == lenbase) continue; /* ignore empty lines */
if (!stat(filename, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r = remove_directory(filename);
else {
printf("Removing: %s\n",filename);
r = unlink(filename);
}
} else
r = -1;
if (r!=0)
fprintf(stderr,"Error removing \"%s\"\n",filename);
}
if (fin != stdin) fclose(fin);
return 0;
} // main