common/file_util: Make GetCurrentDir() return a std::optional
nullptr was being returned in the error case, which, at a glance may seem perfectly OK... until you realize that std::string has the invariant that it may not be constructed from a null pointer. This means that if this error case was ever hit, then the application would most likely crash from a thrown exception in std::string's constructor. Instead, we can change the function to return an optional value, indicating if a failure occurred.
This commit is contained in:
parent
943f6da1ac
commit
11e9bee91d
@ -525,7 +525,7 @@ void CopyDir(const std::string& source_path, const std::string& dest_path) {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string GetCurrentDir() {
|
std::optional<std::string> GetCurrentDir() {
|
||||||
// Get the current working directory (getcwd uses malloc)
|
// Get the current working directory (getcwd uses malloc)
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
wchar_t* dir;
|
wchar_t* dir;
|
||||||
@ -535,7 +535,7 @@ std::string GetCurrentDir() {
|
|||||||
if (!(dir = getcwd(nullptr, 0))) {
|
if (!(dir = getcwd(nullptr, 0))) {
|
||||||
#endif
|
#endif
|
||||||
LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: {}", GetLastErrorMsg());
|
LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: {}", GetLastErrorMsg());
|
||||||
return nullptr;
|
return {};
|
||||||
}
|
}
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
std::string strDir = Common::UTF16ToUTF8(dir);
|
std::string strDir = Common::UTF16ToUTF8(dir);
|
||||||
|
@ -9,6 +9,7 @@
|
|||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <type_traits>
|
#include <type_traits>
|
||||||
@ -118,7 +119,7 @@ u64 ScanDirectoryTree(const std::string& directory, FSTEntry& parent_entry,
|
|||||||
bool DeleteDirRecursively(const std::string& directory, unsigned int recursion = 256);
|
bool DeleteDirRecursively(const std::string& directory, unsigned int recursion = 256);
|
||||||
|
|
||||||
// Returns the current directory
|
// Returns the current directory
|
||||||
std::string GetCurrentDir();
|
std::optional<std::string> GetCurrentDir();
|
||||||
|
|
||||||
// Create directory and copy contents (does not overwrite existing files)
|
// Create directory and copy contents (does not overwrite existing files)
|
||||||
void CopyDir(const std::string& source_path, const std::string& dest_path);
|
void CopyDir(const std::string& source_path, const std::string& dest_path);
|
||||||
|
Loading…
Reference in New Issue
Block a user