-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfile_utils.cpp
103 lines (75 loc) · 2.18 KB
/
file_utils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <cstring>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include "rf_pipelines_internals.hpp"
using namespace std;
namespace rf_pipelines {
#if 0
}; // pacify emacs c-mode!
#endif
bool file_exists(const string &filename)
{
struct stat s;
int err = stat(filename.c_str(), &s);
if (err >= 0)
return true;
if (errno == ENOENT)
return false;
throw runtime_error(filename + ": " + strerror(errno));
}
vector<string> listdir(const string &dirname)
{
vector<string> filenames;
DIR *dir = opendir(dirname.c_str());
if (!dir)
throw runtime_error(dirname + ": opendir() failed: " + strerror(errno));
ssize_t name_max = pathconf(dirname.c_str(), _PC_NAME_MAX);
name_max = min(name_max, (ssize_t)4096);
vector<char> buf(sizeof(struct dirent) + name_max + 1);
struct dirent *entry = reinterpret_cast<struct dirent *> (&buf[0]);
for (;;) {
struct dirent *result = nullptr;
int err = readdir_r(dir, entry, &result);
if (err)
throw runtime_error(dirname + ": readdir_r() failed");
if (!result)
break;
filenames.push_back(entry->d_name);
}
return filenames;
}
// FIXME currently only creates the last directory, e.g. if called with dirname="/a/b/c"
// it assumes that /a/b exists and only creates directory "c".
void makedirs(const string &dirname)
{
int err = mkdir(dirname.c_str(), 0777);
if (!err)
return;
if (errno != EEXIST) {
stringstream ss;
ss << "couldn't create directory " << dirname << ": " << strerror(errno);
string err_msg = ss.str();
cerr << err_msg << "\n";
throw runtime_error(err_msg);
}
struct stat s;
err = stat(dirname.c_str(), &s);
if (err < 0) {
stringstream ss;
ss << "couldn't stat file " << dirname << ": " << strerror(errno);
string err_msg = ss.str();
cerr << err_msg << "\n";
throw runtime_error(err_msg);
}
if (!S_ISDIR(s.st_mode)) {
stringstream ss;
ss << "couldn't create directory " << dirname << ": file already exists and is not a directory";
string err_msg = ss.str();
cerr << err_msg << "\n";
throw runtime_error(err_msg);
}
}
} // namespace rf_pipelines