C++ Utilities 5.24.7
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Loading...
Searching...
No Matches
path.cpp
Go to the documentation of this file.
1#define CPP_UTILITIES_PATHHELPER_STRING_VIEW
2
3#include "./path.h"
4
5#include <cstdlib>
6#include <fstream>
7#include <sstream>
8#include <string>
9
10using namespace std;
11
12namespace CppUtilities {
13
17std::string fileName(const std::string &path)
18{
19 return std::string(fileName(std::string_view(path)));
20}
21
25std::string directory(const std::string &path)
26{
27 return std::string(directory(std::string_view(path)));
28}
29
33std::string_view fileName(std::string_view path)
34{
35 std::size_t lastSlash = path.rfind('/');
36 std::size_t lastBackSlash = path.rfind('\\');
37 std::size_t lastSeparator;
38 if (lastSlash == std::string::npos && lastBackSlash == std::string::npos) {
39 return path;
40 } else if (lastSlash == std::string::npos) {
42 } else if (lastBackSlash == std::string::npos) {
44 } else {
46 }
47 return path.substr(lastSeparator + 1);
48}
49
53std::string_view directory(std::string_view path)
54{
55 std::size_t lastSlash = path.rfind('/');
56 std::size_t lastBackSlash = path.rfind('\\');
57 std::size_t lastSeparator;
58 if (lastSlash == std::string::npos && lastBackSlash == std::string::npos) {
59 return std::string_view();
60 } else if (lastSlash == std::string::npos) {
62 } else if (lastBackSlash == std::string::npos) {
64 } else {
66 }
67 return path.substr(0, lastSeparator + 1);
68}
69
75void removeInvalidChars(std::string &fileName)
76{
77 size_t startPos = 0;
78 static const char invalidPathChars[] = { '\"', '<', '>', '?', '!', '*', '|', '/', ':', '\\', '\n' };
79 for (const char *i = invalidPathChars, *end = invalidPathChars + sizeof(invalidPathChars); i != end; ++i) {
80 startPos = fileName.find(*i);
81 while (startPos != string::npos) {
82 fileName.replace(startPos, 1, string());
83 startPos = fileName.find(*i, startPos);
84 }
85 }
86}
87
88} // namespace CppUtilities
Contains all utilities provides by the c++utilities library.
IntegralType stringToNumber(const StringType &string, BaseType base=10)
Converts the given string to an unsigned/signed number assuming string uses the specified base.
CPP_UTILITIES_EXPORT void removeInvalidChars(std::string &fileName)
Removes invalid characters from the specified fileName.
Definition path.cpp:75
CPP_UTILITIES_EXPORT std::string fileName(const std::string &path)
Returns the file name and extension of the specified path string.
Definition path.cpp:17
CPP_UTILITIES_EXPORT std::string directory(const std::string &path)
Returns the directory of the specified path string (including trailing slash).
Definition path.cpp:25
STL namespace.
constexpr int i