Jpp 21.0.0-rc.3
the software that should make you happy
Loading...
Searching...
No Matches
JFilesystem.hh
Go to the documentation of this file.
1#ifndef __JSYSTEM_JFILEJSYSTEM__
2#define __JSYSTEM_JFILEJSYSTEM__
3
4#include <string>
5#include <vector>
6#include <fstream>
7#include <filesystem>
8#include <set>
9#include <stdexcept>
10#include <dirent.h>
11
12
13namespace JSYSTEM {}
14namespace JPP { using namespace JSYSTEM; }
15
16namespace JSYSTEM {
17
18 /**
19 * Resolve symbolic links.
20 *
21 * \param file_name file name
22 * \return file name
23 */
24 inline std::filesystem::path resolveSymlink(const std::filesystem::path& file_name)
25 {
26 using namespace std::filesystem;
27
28 path ps(file_name);
29
30 if (is_symlink(ps)) {
31 try {
32 ps = canonical(ps);
33 }
34 catch(const std::exception&) {
35 std::set<path> seen;
36
37 while (true) {
38 const path target = read_symlink(ps);
39 const path next = ps.parent_path() / target;
40
41 if (!is_symlink(next)) {
42 ps = target;
43 break;
44 }
45
46 if (!seen.insert(next).second) {
47 throw std::runtime_error("Cyclic symbolic links while resolving " + file_name.string());
48 }
49
50 ps = next;
51 }
52 }
53 }
54
55 return ps;
56 }
57
58
59 /**
60 * Auxiliary data structure to list files in directory.
61 */
62 struct ls :
63 public std::vector<std::string>
64 {
65 /**
66 * Constructor.
67 *
68 * \param dir directory
69 */
70 ls(const std::string& dir)
71 {
72 DIR* top = opendir(dir.c_str());
73
74 if (top != NULL) {
75
76 for (dirent* i; (i = readdir(top)) != NULL; ) {
77 this->push_back(i->d_name);
78 }
79
80 closedir(top);
81 }
82 }
83 };
84
85
86 /**
87 * Rename file across file systems.
88 *
89 * \param inputFile input file
90 * \param outputFile input file
91 * \return zero upon success; else non-zero
92 */
93 inline int rename(const std::string& inputFile,
94 const std::string& outputFile)
95 {
96 using namespace std;
97
98 ifstream in (inputFile .c_str(), ios::binary);
99 ofstream out(outputFile.c_str(), ios::binary);
100
101 out << in.rdbuf();
102
103 if (out)
104 return remove(inputFile.c_str());
105 else
106 return -1;
107 }
108}
109
110#endif
string outputFile
This name space includes all other name spaces (except KM3NETDAQ, KM3NET and ANTARES).
Auxiliary classes and methods for operating system calls.
std::filesystem::path resolveSymlink(const std::filesystem::path &file_name)
Resolve symbolic links.
int rename(const std::string &inputFile, const std::string &outputFile)
Rename file across file systems.
Auxiliary data structure to list files in directory.
ls(const std::string &dir)
Constructor.