1 /* xbt_os_file.cpp -- portable interface to file-related functions */
3 /* Copyright (c) 2017-2023. The SimGrid Team. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include "src/internal_config.h"
9 #include "xbt/asserts.h"
10 #include "xbt/file.hpp" /* this module */
18 #include <boost/algorithm/string.hpp>
21 #include <libgen.h> /* POSIX dirname */
23 static std::vector<std::string> file_path;
25 void simgrid::xbt::path_push(std::string const& str)
27 file_path.push_back(str);
29 void simgrid::xbt::path_pop()
33 std::string simgrid::xbt::path_to_string()
35 return boost::join(file_path, ":");
37 FILE* simgrid::xbt::path_fopen(const std::string& name, const char* mode)
39 if (name[0] == '/') // don't mess with absolute file names
40 return fopen(name.c_str(), mode);
42 /* search relative files in the path */
43 for (auto const& path_elm : file_path) {
44 std::string buff = path_elm + "/" + name;
45 FILE* file = fopen(buff.c_str(), mode);
53 std::ifstream* simgrid::xbt::path_ifsopen(const std::string& name)
55 xbt_assert(not name.empty());
57 auto* fs = new std::ifstream();
58 if (name[0] == '/') // don't mess with absolute file names
59 fs->open(name.c_str(), std::ifstream::in);
61 /* search relative files in the path */
62 for (auto const& path_elm : file_path) {
63 std::string buff = path_elm + "/" + name;
64 fs->open(buff.c_str(), std::ifstream::in);
73 simgrid::xbt::Path::Path()
76 std::array<char, 2048> buffer;
77 const char* cwd = getcwd(buffer.data(), 2048);
78 xbt_assert(cwd != nullptr, "Error during getcwd: %s", strerror(errno));
85 std::string simgrid::xbt::Path::get_dir_name() const
88 return dirname(&p[0]);
91 std::string simgrid::xbt::Path::get_base_name() const
94 return basename(&p[0]);