Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / xbt / xbt_os_file.cpp
1 /* xbt_os_file.cpp -- portable interface to file-related functions          */
2
3 /* Copyright (c) 2017-2023. The SimGrid Team. All rights reserved.          */
4
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. */
7
8 #include "src/internal_config.h"
9 #include "xbt/asserts.h"
10 #include "xbt/file.hpp" /* this module */
11
12 #if HAVE_UNISTD_H
13 #include <array>
14 #include <cerrno>
15 #include <unistd.h>
16 #endif
17
18 #include <boost/algorithm/string.hpp>
19 #include <cstring>
20 #include <fstream>
21 #include <libgen.h> /* POSIX dirname */
22
23 static std::vector<std::string> file_path;
24
25 void simgrid::xbt::path_push(std::string const& str)
26 {
27   file_path.push_back(str);
28 }
29 void simgrid::xbt::path_pop()
30 {
31   file_path.pop_back();
32 }
33 std::string simgrid::xbt::path_to_string()
34 {
35   return boost::join(file_path, ":");
36 }
37 FILE* simgrid::xbt::path_fopen(const std::string& name, const char* mode)
38 {
39   if (name[0] == '/') // don't mess with absolute file names
40     return fopen(name.c_str(), mode);
41
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);
46
47     if (file)
48       return file;
49   }
50   return nullptr;
51 }
52
53 std::ifstream* simgrid::xbt::path_ifsopen(const std::string& name)
54 {
55   xbt_assert(not name.empty());
56
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);
60
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);
65
66     if (not fs->fail())
67       return fs;
68   }
69
70   return fs;
71 }
72
73 simgrid::xbt::Path::Path()
74 {
75 #if HAVE_UNISTD_H
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));
79   path_ = cwd;
80 #else
81   path_ = ".";
82 #endif
83 }
84
85 std::string simgrid::xbt::Path::get_dir_name() const
86 {
87   std::string p(path_);
88   return dirname(&p[0]);
89 }
90
91 std::string simgrid::xbt::Path::get_base_name() const
92 {
93   std::string p(path_);
94   return basename(&p[0]);
95 }