1 /*
2 
3   auto_dir smart pointer class
4 
5   copyright (c) 2004 squell <squell@alumina.nl>
6 
7   use, modification, copying and distribution of this software is permitted
8   under the conditions described in the file 'COPYING'.
9 
10   Usage:
11 
12   Encapsulates POSIX dirent.h functionality in a basic pointer class
13   very much like auto_ptr<>
14 
15 */
16 
17 #ifndef __ZF_AUTO_DIR
18 #define __ZF_AUTO_DIR
19 
20 #if __STDC_VERSION__ >= 199901L
21 #  include <stdint.h>              // for some implementations of dirent.h
22 #endif
23 #include <dirent.h>
24 
25  // simple c++ wrapper for handling dirent.h
26 
27 class auto_dir {
28     struct ref { auto_dir* p; };            // passing to/from functions
29     DIR* dirp;
30 public:
auto_dir(const char * path)31     explicit auto_dir(const char* path)  { dirp = opendir(path); }
~auto_dir()32    ~auto_dir()                           { if(dirp) closedir(dirp); }
33 
34     operator bool() const                { return dirp; }
read()35     dirent* read()                       { return readdir(dirp); }
rewind()36     void rewind()                        { rewinddir(dirp); }
37 
auto_dir(auto_dir & other)38     auto_dir(auto_dir& other)            { dirp = other.release(); }
39     auto_dir& operator=(auto_dir& other) { reset(other.release()); return *this; }
40 
ref()41     operator ref()                       { ref tmp = { this }; return tmp; }
auto_dir(ref r)42     auto_dir(ref r)                      { dirp = r.p->release(); }
43     auto_dir& operator=(ref r)           { return (*this = *r.p); }
44 
release()45     DIR* release()
46     { DIR* tmp(dirp); dirp = 0; return tmp; }
47     void reset(DIR* p = 0)
48     { if(dirp!=p) closedir(dirp); dirp = p; }
49 };
50 
51 #endif
52 
53