-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_util.cpp
More file actions
106 lines (80 loc) · 2.66 KB
/
string_util.cpp
File metadata and controls
106 lines (80 loc) · 2.66 KB
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
104
105
106
#include <dirent.h>
#include <regex>
#include <vector>
#include "string_util.h"
/** https://thispointer.com/c-how-to-get-filename-from-a-path-with-or-without-extension-boost-c17-filesytem-library/ */
std::string getFileName(std::string filePath) {
// Get last position of "/" char
std::size_t sepPos = filePath.rfind("/");
// If the file sepearatoor is found, extract the last part of the string that corresponds
// to the file name
if (sepPos != std::string::npos) {
int n = filePath.size() - (sepPos + 1);
return filePath.substr(sepPos + 1, n);
}
// If the "/" sep. is not found, assumes filename=path
return filePath;
}
/** \brief Get the directory name.
*/
std::string getDirName(std::string filePath) {
// Get last position of "/" char
std::size_t sepPos = filePath.rfind("/");
// If "/" is found, assumes extracts the part that corresponds to the dirname
if (sepPos != std::string::npos) {
return filePath.substr(0, sepPos + 1);
}
// if "/" not found, assumes that file=path, hence no directory
return "";
}
/** \brief Extract the list of files that match a given pattern.
*
* @param file_prefix File prefix
*
* @author Nicolas Barrier
*
*/
std::vector<std::string> get_files(const char *file_prefix) {
std::string path = getDirName(std::string(file_prefix));
std::string name = getFileName(std::string(file_prefix));
// If path is null, forces it to be "./"
if (path == "") {
path = "./";
}
// Compile the regular expression from the prefix name
std::regex regexp_file(name.c_str());
// init output list of strings
std::vector<std::string> output;
DIR *dp;
struct dirent *dirp;
int cpt = 0;
dp = opendir(path.c_str());
// Check if folder can be opened
if (dp == NULL) {
printf("Opendir function fails %s", path.c_str());
exit(1);
}
// Loop over the elements contained in the parent forcing folder
while ((dirp = readdir(dp)) != NULL) {
// If the name of the current file does not match file pattern, skip
if (!regex_match(dirp->d_name, regexp_file)) {
continue;
}
// Iterates the number of matches
cpt += 1;
// Reconstructs path name
std::stringstream ss;
ss.str("");
ss << path << std::string(dirp->d_name);
// add path name into list
output.push_back(ss.str());
}
closedir(dp);
if (cpt == 0) {
printf("No files found matching %s %s\n", path.c_str(), name.c_str());
exit(1);
}
// alphabetical order
sort(output.begin(), output.end());
return output;
}