diff --git a/include/tlibc/filesystem.h b/include/tlibc/filesystem.h index 74fb2a5..ef929f7 100644 --- a/include/tlibc/filesystem.h +++ b/include/tlibc/filesystem.h @@ -31,6 +31,8 @@ #define path_notseps "\\" #endif +#define path_max_len 1024 + // @brief replaces path_notsep with path_sep void path_fix_separators(str* path); @@ -162,3 +164,7 @@ Result(bool) dir_create(cstr path); /// EXAMPLE: dir_createParent("a/b/c") -> creates "a", "a/b" /// @return false if directory was present already, true if it has been created Result(bool) dir_createParent(cstr path); + +/// @return heap-allocated char array +Result(char*) dir_getCurrent(); +Result(void) dir_setCurrent(cstr path); diff --git a/src/filesystem/dir.c b/src/filesystem/dir.c index fe31b32..901f30c 100644 --- a/src/filesystem/dir.c +++ b/src/filesystem/dir.c @@ -64,3 +64,41 @@ Result(bool) dir_createParent(cstr path){ try(bool result, i, dir_create(parent_dir_cstr)); Return RESULT_VALUE(i, result); } + +Result(void) dir_setCurrent(cstr path){ + int r = +#if TLIBC_FS_USE_WINDOWS_H + _chdir(path); +#else + chdir(path); +#endif + if(r != 0) + { + char* errno_s = strerror_malloc(errno); + char* err = sprintf_malloc( + "Can't set current dicectory to '%s': %s", + path, errno_s); + free(errno_s); + return RESULT_ERROR_HEAP(err); + } + return RESULT_VOID; +} + +Result(char*) dir_getCurrent(){ + char* buf = +#if TLIBC_FS_USE_WINDOWS_H + _getcwd(NULL, path_max_len); +#else + getcwd(NULL, path_max_len); +#endif + if(buf == NULL) + { + char* errno_s = strerror_malloc(errno); + char* err = sprintf_malloc( + "Can't get current dicectory: %s", + errno_s); + free(errno_s); + return RESULT_ERROR_HEAP(err); + } + return RESULT_VALUE(p, buf); +}