-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
Describe the bug
It seems that the error_code version of std::filesystem::remove() fails to report the reason why a file couldn't be removed when the file doesn't exist.
Command-line test case
C:\Users\mntt\test>type repro.cpp
#include <filesystem>
#include <iostream>
int main()
{
std::error_code errorCode;
if (!std::filesystem::remove("file_that_does_not_exist", errorCode))
{
std::cout << "File could not be removed because " << errorCode.message();
}
}
C:\Users\mntt\test>cl /EHsc /std:c++latest repro.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.41.34120 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
/std:c++latest is provided as a preview of language features from the latest C++
working draft, and we're eager to hear about bugs and suggestions for improvements.
However, note that these features are provided as-is without support, and subject
to changes or removal as the working draft evolves. See
https://go.microsoft.com/fwlink/?linkid=2045807 for details.
repro.cpp
Microsoft (R) Incremental Linker Version 14.41.34120.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:repro.exe
repro.obj
C:\Users\mntt\test>repro.exe
File could not be removed because unknown error
Expected behavior
repro.exe outputs that the file could not be deleted because it does not exist.
STL version
Microsoft Visual Studio Professional 2022 (64-bit) - Current
Version 17.11.2
Additional context
I asked a question about this on StackOverflow, and got the following comment:
I tried this code on VS2022 Win10 and it looks like it's an implementation problem. If you call GetLastError inside the if then it's set correctly to 2 ERROR_FILE_NOT_FOUND as per Microsoft's documentation. Seems the implementation of __std_fs_remove doesn't correctly populate the error with the last error code set by DeleteFileW If you try the following code, then you get the expected message: auto err = GetLastError(); errorCode = std::error_code(err, std::system_category()); std::cout << "Could not delete file because " << errorCode.message() << " " << err;
So tl;dr, this code does give the expected behavior:
#include <filesystem>
#include <iostream>
#include <Windows.h>
int main()
{
std::error_code errorCode;
if (!std::filesystem::remove("file_that_does_not_exist", errorCode))
{
auto err = GetLastError();
errorCode = std::error_code(err, std::generic_category());
std::cout << "Could not delete file because " << errorCode.message();
}
}C:\Users\mntt\test>repro.exe
Could not delete file because no such file or directory