C++ Utilities 5.11.2
Useful C++ classes and routines such as argument parser, IO and conversion utilities
path.cpp
Go to the documentation of this file.
1#include "./path.h"
2
3#include <cstdlib>
4#include <fstream>
5#include <sstream>
6#include <string>
7
8using namespace std;
9
10namespace CppUtilities {
11
15string fileName(const string &path)
16{
17 size_t lastSlash = path.rfind('/');
18 size_t lastBackSlash = path.rfind('\\');
19 size_t lastSeparator;
20 if (lastSlash == string::npos && lastBackSlash == string::npos) {
21 return path;
22 } else if (lastSlash == string::npos) {
23 lastSeparator = lastBackSlash;
24 } else if (lastBackSlash == string::npos) {
25 lastSeparator = lastSlash;
26 } else {
27 lastSeparator = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
28 }
29 return path.substr(lastSeparator + 1);
30}
31
35string directory(const string &path)
36{
37 size_t lastSlash = path.rfind('/');
38 size_t lastBackSlash = path.rfind('\\');
39 size_t lastSeparator;
40 if (lastSlash == string::npos && lastBackSlash == string::npos) {
41 return string();
42 } else if (lastSlash == string::npos) {
43 lastSeparator = lastBackSlash;
44 } else if (lastBackSlash == string::npos) {
45 lastSeparator = lastSlash;
46 } else {
47 lastSeparator = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
48 }
49 return path.substr(0, lastSeparator + 1);
50}
51
57void removeInvalidChars(std::string &fileName)
58{
59 size_t startPos = 0;
60 static const char invalidPathChars[] = { '\"', '<', '>', '?', '!', '*', '|', '/', ':', '\\', '\n' };
61 for (const char *i = invalidPathChars, *end = invalidPathChars + sizeof(invalidPathChars); i != end; ++i) {
62 startPos = fileName.find(*i);
63 while (startPos != string::npos) {
64 fileName.replace(startPos, 1, string());
65 startPos = fileName.find(*i, startPos);
66 }
67 }
68}
69
70} // namespace CppUtilities
Contains all utilities provides by the c++utilities library.
CPP_UTILITIES_EXPORT std::string directory(const std::string &path)
Returns the directory of the specified path string (including trailing slash).
Definition: path.cpp:35
CPP_UTILITIES_EXPORT std::string fileName(const std::string &path)
Returns the file name and extension of the specified path string.
Definition: path.cpp:15
CPP_UTILITIES_EXPORT void removeInvalidChars(std::string &fileName)
Removes invalid characters from the specified fileName.
Definition: path.cpp:57
STL namespace.
constexpr int i