use g_unlink() rather than unlink() universally, requires <glib/gstdio.h> in several...
[ardour.git] / libs / pbd / clear_dir.cc
1 /*
2     Copyright (C) 2012 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <string>
21 #include <dirent.h>
22 #include <unistd.h>
23 #include <sys/stat.h>
24 #include <errno.h>
25 #include <string.h>
26
27 #include <glib/gstdio.h>
28 #include <glibmm/miscutils.h>
29
30 #include "pbd/error.h"
31 #include "pbd/compose.h"
32 #include "pbd/clear_dir.h"
33
34 #include "i18n.h"
35
36 using namespace PBD;
37 using namespace std;
38
39 int
40 PBD::clear_directory (const string& dir, size_t* size, vector<string>* paths)
41 {
42         struct dirent* dentry;
43         struct stat statbuf;
44         DIR* dead;
45         int ret = 0;
46
47         if ((dead = ::opendir (dir.c_str())) == 0) {
48                 return -1;
49         }
50         
51         while ((dentry = ::readdir (dead)) != 0) {
52                 
53                 /* avoid '.' and '..' */
54                 
55                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
56                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
57                         continue;
58                 }
59                 
60                 string fullpath = Glib::build_filename (dir, dentry->d_name);
61
62                 if (::stat (fullpath.c_str(), &statbuf)) {
63                         continue;
64                 }
65                 
66                 if (!S_ISREG (statbuf.st_mode)) {
67                         continue;
68                 }
69                 
70                 if (::g_unlink (fullpath.c_str())) {
71                         error << string_compose (_("cannot remove file %1 (%2)"), fullpath, strerror (errno))
72                               << endmsg;
73                         ret = 1;
74                 }
75
76                 if (paths) {
77                         paths->push_back (dentry->d_name);
78                 }
79
80                 if (size) {
81                         *size += statbuf.st_size;
82                 }
83         }
84         
85         ::closedir (dead);
86
87         return ret;
88 }