source: trunk/Mars/mbase/MDirIter.cc@ 19640

Last change on this file since 19640 was 19626, checked in by tbretz, 5 years ago
Added the possibility to use only one column in a file which is read with ReadFile
File size: 12.8 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-2008
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 <fstream>
66#include <iostream>
67
68#include <TList.h>
69#include <TNamed.h>
70#include <TRegexp.h>
71#include <TPRegexp.h>
72#include <TSystem.h>
73
74#include "MLog.h"
75#include "MLogManip.h"
76
77ClassImp(MDirIter);
78
79using namespace std;
80
81// --------------------------------------------------------------------------
82//
83// Add a directory, eg dir="../data"
84// Using a filter (wildcards) will only return files matching this filter.
85// recursive is the number of recursive directories (use 0 for none and -1
86// for all)
87// Returns the number of directories added.
88// If a directory is added using a filter and the directory is already
89// existing without a filter the filter is replaced.
90// If any directory to be added is already existing with a different
91// filter a new entry is created, eg:
92// already existing: ../data <*.root>
93// new entry: ../data <G*>
94// The filters are or'ed.
95//
96Int_t MDirIter::AddDirectory(const char *d, const char *filter, Int_t recursive)
97{
98 TString dir(d);
99
100 // Sanity check
101 if (dir.IsNull())
102 return 0;
103
104#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
105 if (dir[dir.Length()-1]!='/')
106 dir += '/';
107#else
108 if (!dir.EndsWith("/"))
109 dir += '/';
110#endif
111 gSystem->ExpandPathName(dir);
112
113 // Try to find dir in the list of existing dirs
114 TObject *o = fList.FindObject(dir);
115 if (o)
116 {
117 const TString t(o->GetTitle());
118
119 // Check whether the existing dir has an associated filter
120 if (t.IsNull())
121 {
122 // Replace old filter by new one
123 ((TNamed*)o)->SetTitle(filter);
124 return 0;
125 }
126
127 // If the filters are the same no action is taken
128 if (t==filter)
129 return 0;
130 }
131
132 fList.Add(new TNamed((const char*)dir, filter ? filter : ""));
133
134 // No recuresive directories, return
135 if (recursive==0)
136 return 1;
137
138 Int_t rc = 1;
139
140 // Create an iterator to iterate over all entries in the directory
141 MDirIter NextD(dir);
142
143 TString c;
144 while (!(c=NextD(kTRUE)).IsNull())
145 {
146 // Do not process . and .. entries
147 if (c.EndsWith("/.") || c.EndsWith("/.."))
148 continue;
149
150 // If entry is a directory add it with a lower recursivity
151 if (IsDir(c)==0)
152 rc += AddDirectory(c, filter, recursive-1);
153 }
154 return rc;
155}
156
157// --------------------------------------------------------------------------
158//
159// Add a single file to the iterator
160//
161Int_t MDirIter::AddFile(const char *name)
162{
163 return AddDirectory(gSystem->DirName(name), gSystem->BaseName(name));
164}
165
166// --------------------------------------------------------------------------
167//
168// Adds all entries from iter to this object
169//
170void MDirIter::Add(const MDirIter &iter)
171{
172 TIter NextD(&iter.fList);
173 TObject *o=0;
174 while ((o=NextD()))
175 fList.Add(o->Clone());
176}
177
178Int_t MDirIter::ReadList(const char *name, const TString &path)
179{
180 const char *con = gSystem->ConcatFileName(path.Data(), name);
181 TString fname(path.IsNull() ? name : con);
182 delete [] con;
183
184 gSystem->ExpandPathName(fname);
185
186 ifstream fin(fname);
187 if (!fin)
188 {
189 gLog << err << "Cannot open file " << fname << ": ";
190 gLog << strerror(errno) << " [errno=" << errno << "]" <<endl;
191 return -1;
192 }
193
194 Int_t rc = 0;
195
196 while (1)
197 {
198 TString line;
199 line.ReadLine(fin);
200 if (!fin)
201 break;
202
203 line = line.Strip(TString::kBoth);
204 if (line[0]=='#' || line.IsNull())
205 continue;
206
207 TObjArray &arr = *line.Tokenize(' ');
208
209 if (arr.GetEntries()==1)
210 {
211 // FIXME: Check for wildcards
212 const TString file = arr[0]->GetName();
213 const Ssiz_t p = file.Last('/');
214
215 if (p<=0)
216 rc += AddDirectory(".", arr[0]->GetName(), 0);
217 else
218 rc += AddDirectory(TString(file(0, p)), file.Data()+p+1, 0);
219 }
220 else
221 {
222 for (int i=1; i<arr.GetEntries(); i++)
223 rc += AddDirectory(arr[0]->GetName(), arr[i]->GetName(), -1);
224 }
225
226 delete &arr;
227 }
228
229 return true;
230}
231
232// --------------------------------------------------------------------------
233//
234// Return the pointer to the current directory. If the pointer is NULL
235// a new directory is opened. If no new directory can be opened NULL is
236// returned.
237//
238void *MDirIter::Open()
239{
240 // Check whether a directory is already open
241 if (fDirPtr)
242 return fDirPtr;
243
244 // Get Next entry of list
245 fCurrentPath=fNext();
246
247 // Open directory if new entry was found
248 return fCurrentPath ? gSystem->OpenDirectory(fCurrentPath->GetName()) : NULL;
249}
250
251// --------------------------------------------------------------------------
252//
253// Close directory is opened. Set fDirPtr=NULL
254//
255void MDirIter::Close()
256{
257 if (fDirPtr)
258 gSystem->FreeDirectory(fDirPtr);
259 fDirPtr = NULL;
260}
261
262// --------------------------------------------------------------------------
263//
264// Returns the concatenation of 'dir' and 'name'
265//
266TString MDirIter::ConcatFileName(const char *dir, const char *name) const
267{
268 return TString(dir)+name;
269}
270
271// --------------------------------------------------------------------------
272//
273// Check whether the given name n matches the filter f.
274//
275// If the filter is encapsulated in ^ and $ it is assumed to be
276// a valid regular expression and TPRegexp is used for filtering.
277//
278// In other cases TRegex is used:
279//
280// As the filter string may contain a + character, we have to replace
281// this filter by a new filter contaning a \+ at all locations where a +
282// was in the original filter.
283//
284// We replace:
285// . by \\.
286// + by \\+
287// * by [^\\/:]*
288//
289// And surround the filter by ^ and $.
290//
291// For more details you can have a look at the template:
292// TRegexp::MakeWildcard
293//
294Bool_t MDirIter::MatchFilter(const TString &n, TString f) const
295{
296 if (f.IsNull())
297 return kTRUE;
298
299 if (f[0]=='^' && f[f.Length()-1]=='$')
300 {
301 TPRegexp regex(f);
302 return !n(regex).IsNull();
303 }
304
305 f.Prepend("^");
306 f.ReplaceAll(".", "\\.");
307 f.ReplaceAll("+", "\\+");
308 f.ReplaceAll("*", "[^\\/:]*");
309 //f.ReplaceAll("?", "[^\\/:]?");
310 f.Append("$");
311
312 return !n(TRegexp(f)).IsNull();
313}
314
315// --------------------------------------------------------------------------
316//
317// Check whether fqp is a directory.
318// Returns -1 if fqp couldn't be accesed, 0 if it is a directory,
319// 1 otherwise
320//
321Int_t MDirIter::IsDir(const char *fqp) const
322{
323 Long_t t[4];
324 if (gSystem->GetPathInfo(fqp, t, t+1, t+2, t+3))
325 return -1;
326
327 if (t[2]==3)
328 return 0;
329
330 return 1;
331}
332
333// --------------------------------------------------------------------------
334//
335// Check whether the current entry in the directory n is valid or not.
336// Entries must:
337// - not be . or ..
338// - match the associated filter
339// - match the global filter
340// - not be a directory
341// - have read permission
342//
343Bool_t MDirIter::CheckEntry(const TString n) const
344{
345 // Check . and ..
346 if (n=="." || n=="..")
347 return kFALSE;
348
349 // Check associated filter
350 if (!MatchFilter(n, fCurrentPath->GetTitle()))
351 return kFALSE;
352
353 // Check global filter
354 if (!MatchFilter(n, fFilter))
355 return kFALSE;
356
357 // Check for file or directory
358 const TString fqp = ConcatFileName(fCurrentPath->GetName(), n);
359 if (IsDir(fqp)<=0)
360 return kFALSE;
361
362 // Check for rread perissions
363 return !gSystem->AccessPathName(fqp, kReadPermission);
364}
365
366// --------------------------------------------------------------------------
367//
368// Reset the iteration and strat from scratch. To do this correctly we have
369// to reset the list of directories to iterate _and_ to close the current
370// directory. When you call Next() the next time the first directory will
371// be reopened again and you'll get the first entry.
372//
373// Do not try to only close the current directory or to reset the directory
374// list only. This might not give the expected result!
375//
376void MDirIter::Reset()
377{
378 Close();
379 fNext.Reset();
380}
381
382// --------------------------------------------------------------------------
383//
384// Return the Next file in the directory which is valid (see Check())
385// nocheck==1 returns the next entry unchecked
386//
387TString MDirIter::Next(Bool_t nocheck)
388{
389 while (1)
390 {
391 fDirPtr = Open();
392 if (!fDirPtr)
393 break;
394
395 // Get next entry in dir, if existing check validity
396 const char *n = gSystem->GetDirEntry(fDirPtr);
397 if (!n)
398 {
399 // Otherwise close directory and try to get next entry
400 Close();
401 continue;
402 }
403
404 if (nocheck || CheckEntry(n))
405 return ConcatFileName(fCurrentPath->GetName(), n);
406 }
407
408 return "";
409}
410
411// --------------------------------------------------------------------------
412//
413// Print a single entry in the list
414//
415void MDirIter::PrintEntry(const TObject &o) const
416{
417 TString p = o.GetName();
418 TString f = o.GetTitle();
419 cout << p;
420 if (!f.IsNull())
421 cout << " <" << f << ">";
422 cout << endl;
423}
424
425// --------------------------------------------------------------------------
426//
427// Print all scheduled directories. If "all" is specified also all
428// matching entries are printed.
429//
430void MDirIter::Print(const Option_t *opt) const
431{
432 TString s(opt);
433 if (s.Contains("dbg", TString::kIgnoreCase))
434 fList.Print();
435
436 if (!s.Contains("all", TString::kIgnoreCase))
437 {
438 TIter NextD(&fList);
439 TObject *o=NULL;
440 while ((o=NextD()))
441 PrintEntry(*o);
442 return;
443 }
444
445 MDirIter NextD(*this);
446 TString name;
447 TString d;
448 while (!(name=NextD()).IsNull())
449 {
450 const TString p = NextD.fCurrentPath->GetName();
451 if (p!=d)
452 {
453 d=p;
454 PrintEntry(*NextD.fCurrentPath);
455 }
456 cout << " " << name << endl;
457 }
458}
459
460// --------------------------------------------------------------------------
461//
462// Loop over all contents (files). Sort the files alphabetically.
463// Delete the contents of this DirIter and add all sorted files
464// to this DirIter.
465//
466void MDirIter::Sort()
467{
468 MDirIter NextD(*this);
469
470 TList l;
471 l.SetOwner();
472
473 TString name;
474 while (!(name=NextD()).IsNull())
475 l.Add(new TNamed(name.Data(), ""));
476
477 l.Sort();
478
479 fList.Delete();
480 Close();
481 fFilter = "";
482
483 TIter NextN(&l);
484 TObject *o=0;
485 while ((o=NextN()))
486 {
487 TString dir = o->GetName();
488 TString fname = o->GetName();
489
490 const Int_t last = dir.Last('/');
491 if (last<0)
492 continue;
493
494 dir.Remove(last);
495 fname.Remove(0, last+1);
496
497 AddDirectory(dir, fname);
498 }
499}
Note: See TracBrowser for help on using the repository browser.