UNIXworkcode

1 /* 2 * Copyright 2024 Olaf Wintermann 3 * 4 * Permission is hereby granted, free of charge, to any person obtaining a 5 * copy of this software and associated documentation files (the "Software"), 6 * to deal in the Software without restriction, including without limitation 7 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 * and/or sell copies of the Software, and to permit persons to whom the 9 * Software is furnished to do so, subject to the following conditions: 10 * 11 * The above copyright notice and this permission notice shall be included in 12 * all copies or substantial portions of the Software. 13 * 14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 20 * DEALINGS IN THE SOFTWARE. 21 */ 22 23 #include "pathutils.h" 24 25 #include "nedit_malloc.h" 26 27 #include <stdlib.h> 28 #include <string.h> 29 30 31 char* ConcatPath(const char *parent, const char *name) 32 { 33 size_t parentlen = strlen(parent); 34 size_t namelen = strlen(name); 35 36 size_t pathlen = parentlen + namelen + 2; 37 char *path = NEditMalloc(pathlen); 38 39 memcpy(path, parent, parentlen); 40 if(parentlen > 0 && parent[parentlen-1] != '/') { 41 path[parentlen] = '/'; 42 parentlen++; 43 } 44 if(name[0] == '/') { 45 name++; 46 namelen--; 47 } 48 memcpy(path+parentlen, name, namelen); 49 path[parentlen+namelen] = '\0'; 50 return path; 51 } 52 53 char* FileName(char *path) { 54 int si = 0; 55 int osi = 0; 56 int i = 0; 57 int p = 0; 58 char c; 59 while((c = path[i]) != 0) { 60 if(c == '/') { 61 osi = si; 62 si = i; 63 p = 1; 64 } 65 i++; 66 } 67 68 char *name = path + si + p; 69 if(name[0] == 0) { 70 name = path + osi + p; 71 if(name[0] == 0) { 72 return path; 73 } 74 } 75 76 return name; 77 } 78 79 char* ParentPath(char *path) { 80 char *name = FileName(path); 81 size_t namelen = strlen(name); 82 size_t pathlen = strlen(path); 83 size_t parentlen = pathlen - namelen; 84 if(parentlen == 0) { 85 parentlen++; 86 } 87 char *parent = NEditMalloc(parentlen + 1); 88 memcpy(parent, path, parentlen); 89 parent[parentlen] = '\0'; 90 return parent; 91 } 92