Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Move two generic functions from surf to xbt
[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 <cstring>
19 #include <fstream>
20 #include <libgen.h> /* POSIX dirname */
21
22 FILE* simgrid::xbt::fopen_path(const std::string& name, const char* mode, const std::vector<std::string>& path)
23 {
24   if (name.c_str()[0] == '/') // don't mess with absolute file names
25     return fopen(name.c_str(), mode);
26
27   /* search relative files in the path */
28   for (auto const& path_elm : path) {
29     std::string buff = path_elm + "/" + name;
30     FILE* file       = fopen(buff.c_str(), mode);
31
32     if (file)
33       return file;
34   }
35   return nullptr;
36 }
37
38 std::ifstream* simgrid::xbt::ifsopen_path(const std::string& name, const std::vector<std::string>& path)
39 {
40   xbt_assert(not name.empty());
41
42   auto* fs = new std::ifstream();
43   if (name.c_str()[0] == '/') // don't mess with absolute file names
44     fs->open(name.c_str(), std::ifstream::in);
45
46   /* search relative files in the path */
47   for (auto const& path_elm : path) {
48     std::string buff = path_elm + "/" + name;
49     fs->open(buff.c_str(), std::ifstream::in);
50
51     if (not fs->fail())
52       return fs;
53   }
54
55   return fs;
56 }
57
58 simgrid::xbt::Path::Path()
59 {
60 #if HAVE_UNISTD_H
61   std::array<char, 2048> buffer;
62   const char* cwd = getcwd(buffer.data(), 2048);
63   xbt_assert(cwd != nullptr, "Error during getcwd: %s", strerror(errno));
64   path_ = cwd;
65 #else
66   path_ = ".";
67 #endif
68 }
69
70 std::string simgrid::xbt::Path::get_dir_name() const
71 {
72   std::string p(path_);
73   return dirname(&p[0]);
74 }
75
76 std::string simgrid::xbt::Path::get_base_name() const
77 {
78   std::string p(path_);
79   return basename(&p[0]);
80 }