Debian Codegraph @

io/path.cpp

raw symbols SCIP
1 #define CPP_UTILITIES_PATHHELPER_STRING_VIEW
2
3 #include "./path.h"
4
5 #include <cstdlib>
6 #include <string>
7
8 using namespace std;
9
10 namespace CppUtilities {
11
12 /*!
13 * \brief Returns the file name and extension of the specified \a path string.
14 */
15 std::string fileName(const std::string &path)
16 {
17 return std::string(fileName(std::string_view(path)));
18 }
19
20 /*!
21 * \brief Returns the directory of the specified \a path string (including trailing slash).
22 */
23 std::string directory(const std::string &path)
24 {
25 return std::string(directory(std::string_view(path)));
26 }
27
28 /*!
29 * \brief Returns the file name and extension of the specified \a path string.
30 */
31 std::string_view fileName(std::string_view path)
32 {
33 std::size_t lastSlash = path.rfind('/');
34 std::size_t lastBackSlash = path.rfind('\\');
35 std::size_t lastSeparator;
36 if (lastSlash == std::string::npos && lastBackSlash == std::string::npos) {
37 return path;
38 } else if (lastSlash == std::string::npos) {
39 lastSeparator = lastBackSlash;
40 } else if (lastBackSlash == std::string::npos) {
41 lastSeparator = lastSlash;
42 } else {
43 lastSeparator = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
44 }
45 return path.substr(lastSeparator + 1);
46 }
47
48 /*!
49 * \brief Returns the directory of the specified \a path string (including trailing slash).
50 */
51 std::string_view directory(std::string_view path)
52 {
53 std::size_t lastSlash = path.rfind('/');
54 std::size_t lastBackSlash = path.rfind('\\');
55 std::size_t lastSeparator;
56 if (lastSlash == std::string::npos && lastBackSlash == std::string::npos) {
57 return std::string_view();
58 } else if (lastSlash == std::string::npos) {
59 lastSeparator = lastBackSlash;
60 } else if (lastBackSlash == std::string::npos) {
61 lastSeparator = lastSlash;
62 } else {
63 lastSeparator = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
64 }
65 return path.substr(0, lastSeparator + 1);
66 }
67
68 /*!
69 * \brief Removes invalid characters from the specified \a fileName.
70 *
71 * The characters <, >, ?, !, *, |, /, :, \ and new lines are considered as invalid.
72 */
73 void removeInvalidChars(std::string &fileName)
74 {
75 size_t startPos = 0;
76 static const char invalidPathChars[] = { '\"', '<', '>', '?', '!', '*', '|', '/', ':', '\\', '\n' };
77 for (const char *i = invalidPathChars, *end = invalidPathChars + sizeof(invalidPathChars); i != end; ++i) {
78 startPos = fileName.find(*i);
79 while (startPos != string::npos) {
80 fileName.replace(startPos, 1, string());
81 startPos = fileName.find(*i, startPos);
82 }
83 }
84 }
85
86 } // namespace CppUtilities