aGrUM  0.20.3
a C++ library for (probabilistic) graphical models
utils_dir.cpp
Go to the documentation of this file.
1 /**
2  *
3  * Copyright (c) 2005-2021 by Pierre-Henri WUILLEMIN(@LIP6) & Christophe GONZALES(@AMU)
4  * info_at_agrum_dot_org
5  *
6  * This library is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this library. If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 
22 /**
23  * @file
24  * @brief Contains usefull methods to work with directories.
25  *
26  * @author Vincent RENAUDINEAU and Pierre-Henri WUILLEMIN(@LIP6)
27  */
28 
29 #include <agrum/tools/core/utils_dir.h>
30 
31 namespace gum {
32 
33  // Return true if \a directory is a valid directory, false otherwise.
34  bool Directory::isDir(const std::string& directory) { return Directory(directory).isValid(); }
35 
36  // Contructor
37  Directory::Directory() : m_dirPtr(nullptr) {
39  ;
40  }
41 
42  // Contructor
46  }
47 
48  // Contructor
52  }
53 
54  // Destructor
57 
58  if (m_dirPtr != nullptr) closedir(m_dirPtr);
59  }
60 
61  // Return true if directory has been opened, false otherwise.
62  bool Directory::isValid() const { return m_dirPtr != nullptr; }
63 
64  // Return directory content.
66  std::vector< std::string > result;
67 
68  if (!isValid()) return result;
69 
71 
72  dirent* entry;
73 
74  while ((entry = readdir(m_dirPtr)))
76 
77  return result;
78  }
79 
80  // Return directory parent.
82  if (!isValid()) return Directory();
83 
84  return Directory(m_dirName + "../");
85  }
86 
87  // Return directory path.
88  std::string Directory::path() const { return m_dirName; }
89 
90  // Return directory absolute path.
92  std::string result;
93 
94  if (!isValid()) return result;
95 
96  char oldWD[255];
97 
98  if (getcwd(oldWD, 255) == nullptr) return result;
99 
100  if (chdir(m_dirName.c_str()) != 0) return result;
101 
102  char absPath[255];
103 
104  if (getcwd(absPath, 254) != nullptr) result = std::string(absPath) + '/';
105 
106  if (chdir(oldWD) != 0)
107  std::cerr << "Warning : Could not go to previous working directory. (" << __FILE__ << ":"
108  << __LINE__ << ")" << std::endl;
109 
110  return result;
111  }
112 
114  if (m_dirPtr != nullptr) closedir(m_dirPtr);
115 
117 
119 
120  return *this;
121  }
122 
123 } // namespace gum
INLINE void emplace(Args &&... args)
Definition: set_tpl.h:643