Added check on ENOENT
[distributed.git] / src / libs / fs / directory.cxx
blobbde3d6b1d5c725a40fc230530a133adb9fce75f7
1 //
2 // Copyright (C) 2007, 2008 Francesco Salvestrini
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.
14 // You should have received a copy of the GNU General Public License along
15 // with this program; if not, write to the Free Software Foundation, Inc.,
16 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include "config.h"
21 #include <string>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 #include <dirent.h>
27 #include <errno.h>
29 #include "libs/misc/debug.h"
30 #include "libs/misc/exception.h"
31 #include "libs/fs/directory.h"
33 namespace FS {
34 Directory::Directory(const std::string & name)
36 if (name == "") {
37 throw Exception("Missing directory name");
40 // Remove trailing '/'
41 std::string::size_type p;
43 p = name.rfind("/");
44 //TR_DBG("name = '%s', p = %d, size = %d\n",
45 // name.c_str(), p, name.size());
47 if (p == (name.size() - 1)) {
48 name_ = name.substr(0, p);
49 return;
52 name_ = name;
55 Directory::~Directory(void)
59 const std::string & Directory::name(void) const
61 return name_;
64 void Directory::create(void) const
66 // XXX FIXME: Consider using the gnulib replacement
67 if (::mkdir(name_.c_str(), 0700) != 0) {
68 throw Exception("Cannot create "
69 "'" + name_ + "' "
70 "directory "
71 "(" +
72 std::string(strerror(errno)) +
73 ")");
77 void Directory::remove(void) const
79 // XXX FIXME: Consider using the gnulib replacement
80 if (::rmdir(name_.c_str()) != 0) {
81 throw Exception("Cannot remove "
82 "'" + name_ + "' "
83 "directory "
84 "(" +
85 std::string(strerror(errno)) +
86 ")");
90 bool Directory::exists(void) const
92 // XXX FIXME: Consider using the gnulib replacement
93 DIR * tmp = opendir(name_.c_str());
94 if (tmp == 0) {
95 BUG_ON(errno == EBADF);
97 if (errno == ENOENT) {
98 return false;
101 throw Exception("Cannot open "
102 "'" + name_ + "' "
103 "directory "
104 "(" +
105 std::string(strerror(errno)) +
106 ")");
109 // XXX FIXME: Maybe a check on closedir() return value ...
110 closedir(tmp);
112 return true;