1 /* 2 * Copyright 2005-2007, Ingo Weinhold, bonefish@cs.tu-berlin.de. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 #include "path_util.h" 7 8 #include <stdlib.h> 9 #include <string.h> 10 11 #include "fssh_errors.h" 12 13 14 namespace FSShell { 15 16 17 fssh_status_t 18 get_last_path_component(const char *path, char *buffer, int bufferLen) 19 { 20 int len = strlen(path); 21 if (len == 0) 22 return FSSH_B_BAD_VALUE; 23 24 // eat trailing '/' 25 while (len > 0 && path[len - 1] == '/') 26 len--; 27 28 if (len == 0) { 29 // path is `/' 30 len = 1; 31 } else { 32 // find previous '/' 33 int pos = len - 1; 34 while (pos > 0 && path[pos] != '/') 35 pos--; 36 if (path[pos] == '/') 37 pos++; 38 39 path += pos; 40 len -= pos; 41 } 42 43 if (len >= bufferLen) 44 return FSSH_B_NAME_TOO_LONG; 45 46 memcpy(buffer, path, len); 47 buffer[len] = '\0'; 48 return FSSH_B_OK; 49 } 50 51 char * 52 make_path(const char *dir, const char *entry) 53 { 54 // get the len 55 int dirLen = strlen(dir); 56 int entryLen = strlen(entry); 57 bool insertSeparator = (dir[dirLen - 1] != '/'); 58 int pathLen = dirLen + entryLen + (insertSeparator ? 1 : 0) + 1; 59 60 // allocate the path 61 char *path = (char*)malloc(pathLen); 62 if (!path) 63 return NULL; 64 65 // compose the path 66 strcpy(path, dir); 67 if (insertSeparator) 68 strcat(path + dirLen, "/"); 69 strcat(path + dirLen, entry); 70 71 return path; 72 } 73 74 75 } // namespace FSShell 76