Crombie Tools
InDirectoryHolder.h
Go to the documentation of this file.
1 /**
2  @file InDirectoryHolder.h
3  Header file that defines InDirectoryHolder class.
4  @author Daniel Abercrombie <dabercro@mit.edu>
5 */
6 
7 #ifndef CROMBIETOOLS_COMMONTOOLS_INDIRECTORYHOLDER_H
8 #define CROMBIETOOLS_COMMONTOOLS_INDIRECTORYHOLDER_H
9 
10 #include <iostream>
11 #include <sys/stat.h>
12 
13 #include "TString.h"
14 
15 #include "Debug.h"
16 
17 //--------------------------------------------------------------------
18 
19 /**
20  @ingroup commongroup
21  Helper function that prepends a directory name to a file.
22 */
23 
24 TString AddDirectory(TString dir, TString FileName)
25 {
26  if (dir == "" || FileName.BeginsWith("/"))
27  return FileName;
28  else
29  return dir + FileName;
30 }
31 
32 /**
33  @ingroup commongroup
34  @class InDirectoryHolder
35  This class is used to facilitate running over files in a directory.
36 
37  Main purpose is to centralize function of adding input directory to the filename
38  when considering said file.
39 */
40 
41 class InDirectoryHolder : virtual public Debug
42 {
43  public:
45  virtual ~InDirectoryHolder() {};
46 
47  /// Sets the input directory where the MCFiles will be searched for, and adds a "/" if needed.
48  inline void SetInDirectory ( TString dir ) { fInDirectory = dir.EndsWith("/") ? dir : dir + "/"; }
49  /// @returns the input directory
50  inline TString GetInDirectory () const { return fInDirectory; }
51 
52  protected:
53  /**
54  A helper function that prepends the input directory to a filename.
55  @param FileName is the name of a file inside
56  the fInDirectory or an absolute path.
57  @returns FileName with the input directory prepended,
58  unless absolute or fInDirectory is empty,
59  where it is left alone.
60  */
61  TString AddInDir ( TString FileName );
62 
63  private:
64  TString fInDirectory = ""; ///< Stores the input directory, and always ends with a '/'
65 };
66 
67 //--------------------------------------------------------------------
68 
69 TString
70 InDirectoryHolder::AddInDir(TString FileName) {
71 
72  struct stat buffer;
73  TString output = AddDirectory(fInDirectory, FileName);
74 
75  int code = stat(output.Data(), &buffer);
76  if (code != 0) {
77  Message(eError, "Cannot find file %s!", output.Data());
78  Message(eError, "Status code: %i", code);
79  exit(20);
80  }
81 
82  return output;
83 }
84 
85 #endif