ABACUS develop
Atomic-orbital Based Ab-initio Computation at UStc
Loading...
Searching...
No Matches
fs_compat.h
Go to the documentation of this file.
1#ifndef MODULEBASE_FS_COMPAT_H
2#define MODULEBASE_FS_COMPAT_H
3
4//==========================================================
5// Small filesystem-portability helpers.
6//
7// The POSIX `mkdir(path, mode)` takes a permission-mode argument that
8// does not exist in the Windows CRT (`_mkdir`/MinGW `mkdir` take only a
9// path). This header provides a single cross-platform directory-creation
10// helper so call sites stay identical on every platform.
11//==========================================================
12
13#include <cerrno>
14#include <string>
15#include <vector>
16
17#ifdef _WIN32
18#include <direct.h> // _mkdir
19#else
20#include <sys/stat.h> // mkdir
21#include <sys/types.h>
22#include <unistd.h> // getcwd
23#endif
24
25namespace ModuleBase
26{
27
29inline std::string absolute_path_for_log(const std::string& path)
30{
31 if (path.empty() || path[0] == '/')
32 {
33 return path;
34 }
35 std::vector<char> cwd(256);
36 while (true)
37 {
38#ifdef _WIN32
39 char* result = _getcwd(cwd.data(), static_cast<int>(cwd.size()));
40#else
41 char* result = getcwd(cwd.data(), cwd.size());
42#endif
43 if (result != nullptr)
44 {
45 return std::string(result) + "/" + path;
46 }
47 if (errno != ERANGE)
48 {
49 return path;
50 }
51 cwd.resize(cwd.size() * 2);
52 }
53}
54
66inline int make_directory(const std::string& path)
67{
68#ifdef _WIN32
69 return _mkdir(path.c_str());
70#else
71 return mkdir(path.c_str(), 0755);
72#endif
73}
74
89inline bool ensure_directory(const std::string& path)
90{
91 if (path.empty())
92 {
93 return true;
94 }
95 const int ret = make_directory(path);
96 return ret == 0 || errno == EEXIST;
97}
98
99} // namespace ModuleBase
100
101#endif // MODULEBASE_FS_COMPAT_H
Definition clebsch_gordan_coeff.cpp:8
int make_directory(const std::string &path)
Create a single directory, portably.
Definition fs_compat.h:66
bool ensure_directory(const std::string &path)
Ensure a directory exists, creating it lazily if needed.
Definition fs_compat.h:89
std::string absolute_path_for_log(const std::string &path)
Return an absolute path for logging, or the original path if getcwd fails.
Definition fs_compat.h:29