rivet is hosted by Hepforge, IPPP Durham
Rivet 4.0.0
osdir.hh
1
19#ifndef OSLINK_OSDIR_HEADER_H_
20#define OSLINK_OSDIR_HEADER_H_
21
23
24#if defined(unix) || defined(__unix) || defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
25#define OSLINK_OSDIR_POSIX
26#elif defined(_WIN32)
27#define OSLINK_OSDIR_WINDOWS
28#else
29#define OSLINK_OSDIR_NOTSUPPORTED
30#endif
31
32#include <string>
33
34#if defined(OSLINK_OSDIR_NOTSUPPORTED)
35
36namespace oslink
37{
38 class directory
39 {
40 public:
41 directory(const std::string&) { }
42 operator void*() const { return (void*)0; }
43 std::string next() { return ""; }
44 };
45}
46
47#elif defined(OSLINK_OSDIR_POSIX)
48
49#include <sys/types.h>
50#include <dirent.h>
51
52namespace oslink
53{
54 class directory
55 {
56 public:
57 directory(const std::string& aName)
58 : handle(opendir(aName.c_str())), willfail(false)
59 {
60 if (!handle)
61 willfail = true;
62 else
63 {
64 dirent* entry = readdir(handle);
65 if (entry)
66 current = entry->d_name;
67 else
68 willfail = true;
69 }
70 }
71 ~directory()
72 {
73 if (handle)
74 closedir(handle);
75 }
76 operator void*() const
77 {
78 return willfail ? (void*)0:(void*)(-1);
79 }
80 std::string next()
81 {
82 std::string prev(current);
83 dirent* entry = readdir(handle);
84 if (entry)
85 current = entry->d_name;
86 else
87 willfail = true;
88 return prev;
89 }
90 private:
91 DIR* handle;
92 bool willfail;
93 std::string current;
94 };
95}
96
97#elif defined(OSLINK_OSDIR_WINDOWS)
98
99#include <windows.h>
100#include <winbase.h>
101
102namespace oslink
103{
104 class directory
105 {
106 public:
107 directory(const std::string& aName)
108 : handle(INVALID_HANDLE_VALUE), willfail(false)
109 {
110 // First check the attributes trying to access a non-directory with
111 // FindFirstFile takes ages
112 DWORD attrs = GetFileAttributes(aName.c_str());
113 if ( (attrs == 0xFFFFFFFF) || ((attrs && FILE_ATTRIBUTE_DIRECTORY) == 0) )
114 {
115 willfail = true;
116 return;
117 }
118 std::string Full(aName);
119 // Circumvent a problem in FindFirstFile with c:\\* as parameter
120 if ( (Full.length() > 0) && (Full[Full.length()-1] != '\\') )
121 Full += "\\";
122 WIN32_FIND_DATA entry;
123 handle = FindFirstFile( (Full+"*").c_str(), &entry);
124 if (handle == INVALID_HANDLE_VALUE)
125 willfail = true;
126 else
127 current = entry.cFileName;
128 }
129 ~directory()
130 {
131 if (handle != INVALID_HANDLE_VALUE)
132 FindClose(handle);
133 }
134
135 operator void*() const
136 {
137 return willfail ? (void*)0:(void*)(-1);
138 }
139 std::string next()
140 {
141 std::string prev = current;
142 WIN32_FIND_DATA entry;
143 int ok = FindNextFile(handle, &entry);
144 if (!ok)
145 willfail = true;
146 else
147 current = entry.cFileName;
148 return current;
149 }
150 private:
151 HANDLE handle;
152 bool willfail;
153 std::string current;
154 };
155}
156
157
158#endif
159
161
162#endif
163