auto path = std::filesystem::path("c:") / "PosteClient.log";
results in c:PosteClient.log instead of c:\PosteClient.log
This is a strange behavior for me as the result on windows can't be used e.g.
CreateFile("c:PosteClient.log")
fails with ERROR_FILE_NOT_FOUND.
I can't find the reason for this behaviour in the docu but from the example it looks like this is the expected behaviour. https://en.cppreference.com/w/cpp/filesystem/path/append
I want to understand why the behaviour is like this to find a proper solution for my code which works for all scenarios of using this operator
Ok lets be more precise, let's assume i have the following code:
HANDLE CreateHandleFromPath(const std::filesystem::path& path, const std::string& fileName)
{
auto pathComplete = path / fileName;
auto* hFile = CreateFileW(
pathComplete.wstring().c_str(),
GENERIC_READ,
FILE_SHARE_READ, nullptr, OPEN_EXISTING,
0,
nullptr);
if (hFile == INVALID_HANDLE_VALUE || hFile == nullptr)
{
throw std::filesystem::filesystem_error(
"Can't get handle",
std::error_code(::GetLastError(), std::system_category()));
}
return hFile;
}
The working directory is
C:\SRC\ConsoleApplication3\
When i call now this code with
CreateHandleFromPath(std::filesystem::path("c:\\"), "test.log")
The function succeed because the result path is "c:\test.log"
CreateHandleFromPath(std::filesystem::path("c:"), "test.log")
The function fails because the result path is "c:test.log"
I don't have control over the caller. For sure it is easy to make here a check and add the separator by hand but this would mean i can do it all the time by myself and don't need the operator or even more precise it is more secure to add it by myself because this will work in all situations, the operator/ works for all except if someone calls with the drive letter without the backslash. I only want to understand why the function is working like that because i think there is a reason behind which i don't see currently