Loading...
Searching...
No Matches
filesystem.hpp
Go to the documentation of this file.
1
2#pragma once
3
4#include <filesystem>
5
6namespace terra::util {
7/// @brief Prepares an empty directory with the passed path.
8///
9/// If the directory does not exist: will create a directory
10/// - if possible => returns true
11/// - if creation fails => returns false
12/// If the directory does exist and is empty: will do nothing => returns true
13/// If the directory does exist and is not empty: will do nothing => returns false
14///
15/// Returns true for all non-zero ranks if root_only == true.
16inline bool prepare_empty_directory( const std::string& path_str, bool root_only = true )
17{
18 if ( root_only && mpi::rank() != 0 )
19 {
20 return true;
21 }
22
23 namespace fs = std::filesystem;
24
25 fs::path dir( path_str );
26 std::error_code ec;
27
28 if ( !fs::exists( dir, ec ) )
29 {
30 // Directory doesn't exist: create it
31 if ( !fs::create_directories( dir, ec ) )
32 {
33 return false;
34 }
35 }
36 else if ( !fs::is_empty( dir, ec ) )
37 {
38 // Directory exists and is not empty
39 return false;
40 }
41
42 // Directory either newly created or exists and is empty
43 return true;
44}
45
46/// @brief Like `prepare_empty_directory()` but aborts if empty directory could not be prepared successfully.
47inline void prepare_empty_directory_or_abort( const std::string& path_str, bool root_only = true )
48{
49 if ( !prepare_empty_directory( path_str, root_only ) )
50 {
51 Kokkos::abort( ( "Could not prepare empty directory with path '" + path_str + "'." ).c_str() );
52 }
53}
54} // namespace terra::util
MPIRank rank()
Definition mpi.hpp:10
Definition solver.hpp:9
bool prepare_empty_directory(const std::string &path_str, bool root_only=true)
Prepares an empty directory with the passed path.
Definition filesystem.hpp:16
void prepare_empty_directory_or_abort(const std::string &path_str, bool root_only=true)
Like prepare_empty_directory() but aborts if empty directory could not be prepared successfully.
Definition filesystem.hpp:47