]> git.saurik.com Git - apple/system_cmds.git/blob - CPPUtil/UtilPath.cpp
f08ff24aa858bdf51710b47c7645d7ab84687576
[apple/system_cmds.git] / CPPUtil / UtilPath.cpp
1 //
2 // UtilPath.inline.hpp
3 // CPPUtil
4 //
5 // Created by James McIlree on 4/8/13.
6 // Copyright (c) 2013 Apple. All rights reserved.
7 //
8
9 #include "CPPUtil.h"
10
11 #include <sys/stat.h>
12
13 BEGIN_UTIL_NAMESPACE
14
15 std::string Path::basename(const char* path) {
16 size_t length = strlen(path);
17
18 /*
19 * case: ""
20 * case: "/"
21 * case: [any-single-character-paths]
22 */
23 if (length < 2)
24 return std::string(path);
25
26 char temp[PATH_MAX];
27 char* temp_cursor = &temp[PATH_MAX - 1];
28 char* temp_end = temp_cursor;
29 *temp_end = 0; // NULL terminate
30
31 const char* path_cursor = &path[length-1];
32
33 while (path_cursor >= path) {
34 if (*path_cursor == '/') {
35 // If we have copied one or more chars, we're done
36 if (temp_cursor != temp_end)
37 return std::string(temp_cursor);
38 } else {
39 *(--temp_cursor) = *path_cursor;
40 }
41
42 // Is the temp buffer full?
43 if (temp_cursor == temp)
44 return std::string(temp);
45
46 --path_cursor;
47 }
48
49 if (path[0] == '/' && temp_cursor == temp_end) {
50 *(--temp_cursor) = '/';
51 }
52
53 return std::string(temp_cursor);
54 }
55
56 std::string Path::basename(std::string& path) {
57 return basename(path.c_str());
58 }
59
60 bool Path::exists(const char *path) {
61 struct stat statinfo;
62 return lstat(path, &statinfo) == 0;
63 }
64
65 bool Path::exists(std::string& path) {
66 return exists(path.c_str());
67 }
68
69 bool Path::is_file(const char* path, bool should_resolve_symlinks) {
70 struct stat statinfo;
71 if (should_resolve_symlinks) {
72 if (stat(path, &statinfo) == 0) {
73 if (S_ISREG(statinfo.st_mode)) {
74 return true;
75 }
76 }
77 } else {
78 if (lstat(path, &statinfo) == 0) {
79 if (S_ISREG(statinfo.st_mode)) {
80 return true;
81 }
82 }
83 }
84
85 return false;
86 }
87
88 bool Path::is_file(std::string& path, bool should_resolve_symlinks) {
89 return is_file(path.c_str(), should_resolve_symlinks);
90 }
91
92 END_UTIL_NAMESPACE