/* SPDX-License-Identifier: copyleft-next-0.3.1 */ /* Copyright 2023 Kim Kuparinen < kimi.h.kuparinen@gmail.com > */ /** * @file path.c * * Path handling helper implementations. */ #include #include #include #include #include #include #include #include #include char *fwd_basename(const char *file) { size_t l = strlen(file); size_t n = l - 1; while (--n) { if (file[n] == '/') break; } char *s = NULL; if (n == 0) s = strdupc(file); else s = strndupc(file + n + 1, l - n); if (!s) { internal_error("failed allocating basename"); return NULL; } track_ptr(s); return s; } char *fwd_dirname(const char *file) { size_t l = strlen(file); size_t n = l - 1; while (--n) { if (file[n] == '/') break; } char *s = strndupc(file, n); if (!s) { internal_error("failed allocating dirname"); return NULL; } track_ptr(s); return s; } char *fwd_cwdname() { size_t size; long path_max = pathconf(".", _PC_PATH_MAX); if (path_max == -1) size = 1024; else size = (size_t)path_max; char *buf = mallocc(size); if (!buf) { internal_error("failed allocating cwd buf"); return NULL; } track_ptr(buf); if (!getcwd(buf, size)) { error("%s\n", strerror(errno)); return NULL; } return buf; }