forked from llnl/paraDIS_lib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathutil.h
More file actions
62 lines (54 loc) · 1.94 KB
/
Copy pathpathutil.h
File metadata and controls
62 lines (54 loc) · 1.94 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
/* Written by Richard David Cook
at Lawrence Livermore National Laboratory
Contact: wealthychef@gmail.com
See license.txt for information about usage.
Spoiler alert: it's GNU opensource.
*/
#ifndef RDC_PATHUTIL_H
#define RDC_PATHUTIL_H
#include "stringutil.h"
#include <limits.h>
//===============================================================
/*!
Returns the full path to the directory containing the given file or directory, without the trailing "/", unless the result is "/" itself.
Examples:
Dirname("/usr/local") == "/usr"
Dirname("/usr/local/") == "/usr"
Dirname("relative/path") == "/full/path/to/relative"
Dirname("my/directory/") == "/full/path/to/my"
Dirname("/") == "/"
*/
inline string Dirname(string filename) {
string dirname = StripBack(filename, "/");
if (!dirname.length()) return string("/");
if (dirname[0] != '/') {
// need to switch to absolute path
char wd[PATH_MAX]; // this is why I hate C programming -- there is no way to be sure about buffer overflows with this kind of crap lingering around
getcwd(wd, PATH_MAX);
string::size_type loc = dirname.find("/");
if (loc == string::npos) {
return string(wd);
}
// prepend current working directory to mDirname
dirname = string(wd) + "/" + dirname;
}
string::size_type loc = dirname.rfind("/");
if (loc == string::npos) { // reality check
throw string("Error in Dirname(): Logic error: there are no '/' chars in supposedly absolute path: ") + dirname;
}
return StripBack(dirname.substr(0,loc),"/");
}
//===============================================================
/*!
Returns the last link of the filename, ala the "basename" shell command.
*/
inline string Basename(string filename) {
filename = StripBack(filename, "/");
string::size_type loc = filename.rfind("/");
if (loc == string::npos) {
return filename;
}
string filename2 = filename.substr(loc+1);
return filename2;
}
#endif