From 7afb79aee6d67529305342ab64dc0c3bac2f4001 Mon Sep 17 00:00:00 2001 From: Connor McLaughlin Date: Fri, 24 Jan 2020 14:50:58 +1000 Subject: [PATCH] Common: Add FileSystem::{Get,Set}WorkingDirectory functions --- src/common/file_system.cpp | 40 ++++++++++++++++++++++++++++++++++++++ src/common/file_system.h | 6 ++++++ 2 files changed, 46 insertions(+) diff --git a/src/common/file_system.cpp b/src/common/file_system.cpp index 5f1d51b10..bf2c06f0b 100644 --- a/src/common/file_system.cpp +++ b/src/common/file_system.cpp @@ -1015,6 +1015,26 @@ std::string GetProgramPath() return buffer; } +std::string GetWorkingDirectory() +{ + DWORD required_size = GetCurrentDirectoryA(0, nullptr); + if (!required_size) + return {}; + + std::string buffer; + buffer.resize(required_size - 1); + + if (!GetCurrentDirectoryA(static_cast(buffer.size() + 1), buffer.data())) + return {}; + + return buffer; +} + +bool SetWorkingDirectory(const char* path) +{ + return (SetCurrentDirectoryA(path) == TRUE); +} + #else std::unique_ptr CreateChangeNotifier(const char* path, bool recursiveWatch) @@ -1394,6 +1414,26 @@ std::string GetProgramPath() #endif } +std::string GetWorkingDirectory() +{ + std::string buffer; + buffer.resize(PATH_MAX); + while (!getcwd(buffer.data(), buffer.size())) + { + if (errno != ERANGE) + return {}; + + buffer.resize(buffer.size() * 2); + } + + return buffer; +} + +bool SetWorkingDirectory(const char* path) +{ + return (chdir(path) == 0); +} + #endif } // namespace FileSystem \ No newline at end of file diff --git a/src/common/file_system.h b/src/common/file_system.h index 9b3697c25..4d4553212 100644 --- a/src/common/file_system.h +++ b/src/common/file_system.h @@ -176,4 +176,10 @@ bool DeleteDirectory(const char* Path, bool Recursive); /// Returns the path to the current executable. std::string GetProgramPath(); +/// Retrieves the current working directory. +std::string GetWorkingDirectory(); + +/// Sets the current working directory. Returns true if successful. +bool SetWorkingDirectory(const char* path); + }; // namespace FileSystem