source: trunk/MagicSoft/Mars/mbase/MDirIter.cc@ 4909

Last change on this file since 4909 was 4817, checked in by tbretz, 20 years ago
*** empty log message ***
File size: 9.7 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2003
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MDirIter
28//
29// Iterator for files in several directories (with filters)
30//
31// Use this class if you want to get all filenames in a directory
32// one-by-one.
33//
34// You can specify more than one directory (also recursivly) and you
35// can use filters (eg. *.root)
36//
37// Here is an example which will print all *.root files in the current
38// directory and all its subdirectories and all Gamma*.root files in
39// the directory ../data.
40//
41// ------------------------------------------------------------------------
42//
43// // Instatiate the iterator
44// MDirIter Next();
45//
46// // Add the current directory (for *.root files) and recursive
47// // directories with the same filter
48// Next.AddDirectory(".", "*.root", kTRUE);
49// // Add the directory ../data, too (filter only Gamma*.root files)
50// Next.AddDirectory("../data", "Gamma*.root");
51//
52// TString name;
53// while (!(name=Next()).IsNull())
54// cout << name << endl;
55//
56// ------------------------------------------------------------------------
57//
58// WARNING: If you specify relative directories (like in the example) the
59// result may depend on the current working directory! Better use
60// absolute paths.
61//
62/////////////////////////////////////////////////////////////////////////////
63#include "MDirIter.h"
64
65#include <iostream>
66
67#include <TNamed.h>
68#include <TRegexp.h>
69#include <TSystem.h>
70
71ClassImp(MDirIter);
72
73using namespace std;
74
75// --------------------------------------------------------------------------
76//
77// Add a directory, eg dir="../data"
78// Using a filter (wildcards) will only return files matching this filter.
79// recursive is the number of recursive directories (use 0 for none and -1
80// for all)
81// Returns the number of directories added.
82// If a directory is added using a filter and the directory is already
83// existing without a filter the filter is replaced.
84// If any directory to be added is already existing with a different
85// filter a new entry is created, eg:
86// already existing: ../data <*.root>
87// new entry: ../data <G*>
88// The filters are or'ed.
89//
90Int_t MDirIter::AddDirectory(const char *d, const char *filter, Int_t recursive)
91{
92 TString dir(d);
93
94 // Sanity check
95 if (dir.IsNull())
96 return 0;
97
98#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
99 if (dir[dir.Length()-1]!='/')
100 dir += '/';
101#else
102 if (!dir.EndsWith("/"))
103 dir += '/';
104#endif
105 gSystem->ExpandPathName(dir);
106
107 // Try to find dir in the list of existing dirs
108 TObject *o = fList.FindObject(dir);
109 if (o)
110 {
111 const TString t(o->GetTitle());
112
113 // Check whether the existing dir has an associated filter
114 if (t.IsNull())
115 {
116 // Replace old filter by new one
117 ((TNamed*)o)->SetTitle(filter);
118 return 0;
119 }
120
121 // If the filters are the same no action is taken
122 if (t==filter)
123 return 0;
124 }
125
126 fList.Add(new TNamed((const char*)dir, filter ? filter : ""));
127
128 // No recuresive directories, return
129 if (recursive==0)
130 return 1;
131
132 Int_t rc = 1;
133
134 // Create an iterator to iterate over all entries in the directory
135 MDirIter Next(dir);
136
137 TString c;
138 while (!(c=Next(kTRUE)).IsNull())
139 {
140 // Do not process . and .. entries
141 if (c.EndsWith("/.") || c.EndsWith("/.."))
142 continue;
143
144 // If entry is a directory add it with a lower recursivity
145 if (IsDir(c)==0)
146 rc += AddDirectory(c, filter, recursive-1);
147 }
148 return rc;
149}
150
151// --------------------------------------------------------------------------
152//
153// Adds all entries from iter to this object
154//
155void MDirIter::Add(const MDirIter &iter)
156{
157 TIter Next(&iter.fList);
158 TObject *o=0;
159 while ((o=Next()))
160 fList.Add(o->Clone());
161}
162
163// --------------------------------------------------------------------------
164//
165// Return the pointer to the current directory. If the pointer is NULL
166// a new directory is opened. If no new directory can be opened NULL is
167// returned.
168//
169void *MDirIter::Open()
170{
171 // Check whether a directory is already open
172 if (fDirPtr)
173 return fDirPtr;
174
175 // Get Next entry of list
176 fCurrentPath=fNext();
177
178 // Open directory if new entry was found
179 return fCurrentPath ? gSystem->OpenDirectory(fCurrentPath->GetName()) : NULL;
180}
181
182// --------------------------------------------------------------------------
183//
184// Close directory is opened. Set fDirPtr=NULL
185//
186void MDirIter::Close()
187{
188 if (fDirPtr)
189 gSystem->FreeDirectory(fDirPtr);
190 fDirPtr = NULL;
191}
192
193// --------------------------------------------------------------------------
194//
195// Returns the concatenation of 'dir' and 'name'
196//
197TString MDirIter::ConcatFileName(const char *dir, const char *name) const
198{
199 return TString(dir)+name;
200}
201
202// --------------------------------------------------------------------------
203//
204// Check whether the given name n matches the filter f.
205// Filters are of the form TRegexp(f, kTRUE)
206//
207Bool_t MDirIter::MatchFilter(const TString &n, const TString &f) const
208{
209 // As the filter string may contain a + character, we have to replace
210 // this filter by a new filter contaning a \+ at all locations where a +
211 // was in the original filter.
212 TString nf(f);
213 nf.ReplaceAll("+","\\+");
214
215 return f.IsNull() || !n(TRegexp(nf, kTRUE)).IsNull();
216}
217
218// --------------------------------------------------------------------------
219//
220// Check whether fqp is a directory.
221// Returns -1 if fqp couldn't be accesed, 0 if it is a directory,
222// 1 otherwise
223//
224Int_t MDirIter::IsDir(const char *fqp) const
225{
226 Long_t t[4];
227 if (gSystem->GetPathInfo(fqp, t, t+1, t+2, t+3))
228 return -1;
229
230 if (t[2]==3)
231 return 0;
232
233 return 1;
234}
235
236// --------------------------------------------------------------------------
237//
238// Check whether the current entry in the directory n is valid or not.
239// Entries must:
240// - not be . or ..
241// - match the associated filter
242// - match the global filter
243// - not be a directory
244// - have read permission
245//
246Bool_t MDirIter::Check(const TString n) const
247{
248 // Check . and ..
249 if (n=="." || n=="..")
250 return kFALSE;
251
252 // Check associated filter
253 if (!MatchFilter(n, fCurrentPath->GetTitle()))
254 return kFALSE;
255
256 // Check global filter
257 if (!MatchFilter(n, fFilter))
258 return kFALSE;
259
260 // Check for file or directory
261 const TString fqp = ConcatFileName(fCurrentPath->GetName(), n);
262 if (IsDir(fqp)<=0)
263 return kFALSE;
264
265 // Check for rread perissions
266 return !gSystem->AccessPathName(fqp, kReadPermission);
267
268}
269
270// --------------------------------------------------------------------------
271//
272// Reset the iteration and strat from scratch. To do this correctly we have
273// to reset the list of directories to iterate _and_ to close the current
274// directory. When you call Next() the next time the first directory will
275// be reopened again and you'll get the first entry.
276//
277// Do not try to only close the current directory or to reset the directory
278// list only. This might not give the expected result!
279//
280void MDirIter::Reset()
281{
282 Close();
283 fNext.Reset();
284}
285
286// --------------------------------------------------------------------------
287//
288// Return the Next file in the directory which is valid (see Check())
289// nocheck==1 returns the next entry unchecked
290//
291TString MDirIter::Next(Bool_t nocheck)
292{
293 fDirPtr = Open();
294 if (!fDirPtr)
295 return "";
296
297 // Get next entry in dir, if existing check validity
298 const char *n = gSystem->GetDirEntry(fDirPtr);
299 if (n)
300 return nocheck || Check(n) ? ConcatFileName(fCurrentPath->GetName(), n) : Next();
301
302 // Otherwise close directory and try to get next entry
303 Close();
304 return Next();
305}
306
307// --------------------------------------------------------------------------
308//
309// Print a single entry in the list
310//
311void MDirIter::PrintEntry(const TObject &o) const
312{
313 TString p = o.GetName();
314 TString f = o.GetTitle();
315 cout << p;
316 if (!f.IsNull())
317 cout << " <" << f << ">";
318 cout << endl;
319}
320
321// --------------------------------------------------------------------------
322//
323// Print all scheduled directories. If "all" is specified also all
324// matching entries are printed.
325//
326void MDirIter::Print(const Option_t *o) const
327{
328 TString s(o);
329 if (!s.Contains("all", TString::kIgnoreCase))
330 {
331 TIter Next(&fList);
332 TObject *o=NULL;
333 while ((o=Next()))
334 PrintEntry(*o);
335 return;
336 }
337
338 MDirIter Next(*this);
339 TString name;
340 TString d;
341 while (!(name=Next()).IsNull())
342 {
343 const TString p = Next.fCurrentPath->GetName();
344 if (p!=d)
345 {
346 d=p;
347 PrintEntry(*Next.fCurrentPath);
348 }
349 cout << " " << name << endl;
350 }
351}
Note: See TracBrowser for help on using the repository browser.