add new files
[ardour.git] / libs / pbd / clear_dir.cc
1 #include <string>
2 #include <dirent.h>
3 #include <unistd.h>
4 #include <sys/stat.h>
5 #include <errno.h>
6 #include <string.h>
7
8 #include "pbd/error.h"
9 #include "pbd/compose.h"
10 #include "pbd/clear_dir.h"
11
12 #include "i18n.h"
13
14 using namespace PBD;
15 using namespace std;
16
17 int
18 PBD::clear_directory (const string& dir, size_t* size, vector<string>* paths)
19 {
20         struct dirent* dentry;
21         struct stat statbuf;
22         DIR* dead;
23         int ret = 0;
24
25         if ((dead = ::opendir (dir.c_str())) == 0) {
26                 return -1;
27         }
28         
29         while ((dentry = ::readdir (dead)) != 0) {
30                 
31                 /* avoid '.' and '..' */
32                 
33                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
34                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
35                         continue;
36                 }
37                 
38                 string fullpath;
39
40                 fullpath = dir;
41                 fullpath += '/';
42                 fullpath += dentry->d_name;
43                 
44                 if (::stat (fullpath.c_str(), &statbuf)) {
45                         continue;
46                 }
47                 
48                 if (!S_ISREG (statbuf.st_mode)) {
49                         continue;
50                 }
51                 
52                 if (::unlink (fullpath.c_str())) {
53                         error << string_compose (_("cannot remove file %1 (%2)"), fullpath, strerror (errno))
54                               << endmsg;
55                         ret = 1;
56                 }
57
58                 if (paths) {
59                         paths->push_back (dentry->d_name);
60                 }
61
62                 if (size) {
63                         *size += statbuf.st_size;
64                 }
65         }
66         
67         ::closedir (dead);
68
69         return ret;
70 }