wibble  0.1.28
fs.h
Go to the documentation of this file.
1 #ifndef WIBBLE_SYS_DIRECTORY_H
2 #define WIBBLE_SYS_DIRECTORY_H
3 
4 #include <string>
5 #include <dirent.h> // opendir, closedir
6 #include <memory> // auto_ptr
7 #include <sys/types.h> // mode_t
8 #include <sys/stat.h> // struct stat
9 
10 struct stat;
11 
12 namespace wibble {
13 namespace sys {
14 namespace fs {
15 
21 std::auto_ptr<struct stat> stat(const std::string& pathname);
22 
24 bool access(const std::string& s, int m);
25 
27 bool exists(const std::string& s);
28 
32 std::string abspath(const std::string& pathname);
33 
37 void mkdirIfMissing(const std::string& dir, mode_t mode);
38 
41 void mkpath(const std::string& dir);
42 
45 void mkFilePath(const std::string& file);
46 
48 std::string readFile(const std::string &file);
49 
51 void writeFile(const std::string &file, const std::string &data);
52 
58 bool deleteIfExists(const std::string& file);
59 
61 void renameIfExists(const std::string& src, const std::string& dst);
62 
64 void unlink(const std::string& fname);
65 
67 void rmdir(const std::string& dirname);
68 
70 void rmtree(const std::string& dir);
71 
77 bool isdir(const std::string& pathname);
78 
80 bool isDirectory(const std::string& pathname) __attribute__ ((deprecated));
81 
83 class Directory
84 {
85  std::string m_path;
86 
87 public:
89  {
90  DIR* dir;
91  struct dirent* d;
92 
93  public:
94  // Create an end iterator
95  const_iterator() : dir(0), d(0) {}
96  // Create a begin iterator
97  const_iterator(DIR* dir) : dir(dir), d(0) { ++(*this); }
98  // Cleanup properly
99  ~const_iterator() { if (dir) closedir(dir); }
100 
101  // auto_ptr style copy semantics
103  {
104  dir = i.dir;
105  d = i.d;
106  const_iterator* wi = const_cast<const_iterator*>(&i);
107  wi->dir = 0;
108  wi->d = 0;
109  }
111  {
112  // Catch a = a
113  if (&i == this) return *this;
114  if (dir) closedir(dir);
115  dir = i.dir;
116  d = i.d;
117  const_iterator* wi = const_cast<const_iterator*>(&i);
118  wi->dir = 0;
119  wi->d = 0;
120  return *this;
121  }
122 
124  {
125  if ((d = readdir(dir)) == 0)
126  {
127  closedir(dir);
128  dir = 0;
129  }
130  return *this;
131  }
132 
133  std::string operator*() const { return d->d_name; }
134  struct dirent* operator->() { return d; }
135  const struct dirent* operator->() const { return d; }
136 
137  bool operator==(const const_iterator& iter) const
138  {
139  return dir == iter.dir && d == iter.d;
140  }
141  bool operator!=(const const_iterator& iter) const
142  {
143  return dir != iter.dir || d != iter.d;
144  }
145  };
146 
147  Directory(const std::string& path) : m_path(path) {}
148 
150  const std::string& path() const { return m_path; }
151 
153  bool valid();
154 
156  const_iterator begin();
157 
159  const_iterator end() const;
160 
162  bool isdir(const const_iterator& i) const;
163 };
164 
165 }
166 }
167 }
168 
169 // vim:set ts=4 sw=4:
170 #endif