diff --git a/CMakeLists.txt b/CMakeLists.txt index 8804fe7..5b383ab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,6 +45,7 @@ add_executable(lls src/Table.cpp src/Terminal.cpp src/Tokenizer.cpp + src/HomeDirectory.cpp ) target_include_directories(lls PRIVATE include) diff --git a/build.sh b/build.sh old mode 100644 new mode 100755 diff --git a/include/HomeDirectory.h b/include/HomeDirectory.h new file mode 100644 index 0000000..cfd1038 --- /dev/null +++ b/include/HomeDirectory.h @@ -0,0 +1,13 @@ +#pragma once +#include + +/** + * @brief Retrieves the current user's home directory across different operating systems. + * + * On Windows, it checks the USERPROFILE environment variable. + * On Unix/Linux/macOS, it checks the HOME environment variable, with a fallback + * to checking the password database entry (`getpwuid`) if HOME is unset. + * + * @return std::filesystem::path Path to the user's home directory, or an empty path if unable to resolve. + */ +std::filesystem::path getHomeDirectory(); diff --git a/src/HomeDirectory.cpp b/src/HomeDirectory.cpp new file mode 100644 index 0000000..d292f2f --- /dev/null +++ b/src/HomeDirectory.cpp @@ -0,0 +1,29 @@ +#include "HomeDirectory.h" +#include +#include + +#if defined(_WIN32) + // Windows implementation +#elif defined(__unix__) || defined(__APPLE__) +#include +#include +#include +#endif + +std::filesystem::path getHomeDirectory() { +#if defined(_WIN32) + if (const char* env = std::getenv("USERPROFILE")) { + return std::filesystem::path(env); + } +#else + if (const char* env = std::getenv("HOME")) { + return std::filesystem::path(env); + } + + // Fallback for Unix-like systems if HOME environment variable is unset + if (struct passwd* pwd = getpwuid(getuid()); pwd && pwd->pw_dir) { + return std::filesystem::path(pwd->pw_dir); + } +#endif + return {}; +} diff --git a/src/main.cpp b/src/main.cpp index 46fe7b5..4cb1fa4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,13 +2,14 @@ #include #include +#include "HomeDirectory.h" #include "Config.h" #include "Database.h" #include "Display.h" #include "Repl.h" int main(int argc, char** argv) { - const std::string path = (argc > 1) ? argv[1] : "tasks.db"; + const std::string path = (argc > 1) ? argv[1] : (getHomeDirectory() / "tasks.db"); try { Config config;