Minor refactoring of fs_chdir and fs_getcwd functions

Remove unnecessary `fs_is_dir` check in the `fs_chdir` function. The `SetCurrentDirectoryW` and `chdir` functions would already include such necessary checks anyway.

Assert that `GetCurrentDirectoryW` was successful instead of logging an error message. This function should only potentially fail if the current working directory was changed by another thread between the two calls, which should not happen in our code.
This commit is contained in:
Robert Müller 2024-05-21 18:02:15 +02:00
parent b4a41ea098
commit f04bea6b4b

View file

@ -2389,17 +2389,12 @@ int fs_is_relative_path(const char *path)
int fs_chdir(const char *path) int fs_chdir(const char *path)
{ {
if(fs_is_dir(path))
{
#if defined(CONF_FAMILY_WINDOWS) #if defined(CONF_FAMILY_WINDOWS)
const std::wstring wide_path = windows_utf8_to_wide(path); const std::wstring wide_path = windows_utf8_to_wide(path);
return SetCurrentDirectoryW(wide_path.c_str()) != 0 ? 0 : 1; return SetCurrentDirectoryW(wide_path.c_str()) != 0 ? 0 : 1;
#else #else
return chdir(path) ? 1 : 0; return chdir(path) ? 1 : 0;
#endif #endif
}
else
return 1;
} }
char *fs_getcwd(char *buffer, int buffer_size) char *fs_getcwd(char *buffer, int buffer_size)
@ -2407,15 +2402,7 @@ char *fs_getcwd(char *buffer, int buffer_size)
#if defined(CONF_FAMILY_WINDOWS) #if defined(CONF_FAMILY_WINDOWS)
const DWORD size_needed = GetCurrentDirectoryW(0, nullptr); const DWORD size_needed = GetCurrentDirectoryW(0, nullptr);
std::wstring wide_current_dir(size_needed, L'0'); std::wstring wide_current_dir(size_needed, L'0');
DWORD result = GetCurrentDirectoryW(size_needed, wide_current_dir.data()); dbg_assert(GetCurrentDirectoryW(size_needed, wide_current_dir.data()) == size_needed - 1, "GetCurrentDirectoryW failure");
if(result == 0)
{
const DWORD LastError = GetLastError();
const std::string ErrorMsg = windows_format_system_message(LastError);
dbg_msg("filesystem", "GetCurrentDirectoryW failed: %ld %s", LastError, ErrorMsg.c_str());
buffer[0] = '\0';
return nullptr;
}
const std::optional<std::string> current_dir = windows_wide_to_utf8(wide_current_dir.c_str()); const std::optional<std::string> current_dir = windows_wide_to_utf8(wide_current_dir.c_str());
if(!current_dir.has_value()) if(!current_dir.has_value())
{ {