c++std-filesystem

Why does std::filesystem::remove() error_code return "unknown error" if the file does not exist?


I want to use the std::filesystem::remove() function to remove a file, and give an error if the file does not exist. Something like this:

std::error_code errorCode;
if (!std::filesystem::remove("<some file path>", errorCode))
{
    std::cout << "Could not delete file because " << errorCode.message();
}

However, if the file does not exist, this yields the message Could not delete file because unknown error.

My question is: Why doesn't this tell me that the file does not exist?

I interpret the documentation on cppreference to say that

Given that the error code just says "unknown error" when a file does not exist, it seems that this version gives less information than the non-error_code one? Or maybe I'm misunderstanding something?

I'm on Windows 11, using Visual Studio 2022 Version 17.11.2.


Solution

  • I interpret the documentation on cppreference to say that

    • The non-error_code version of the remove function returns false if the file does not exist, and throws an exception on other errors.
    • The error_code version returns false on any error, and stores the reason in the error_code. It never throws an exception.

    No, that would be inconsistent. Why should one overload treat "file does not exist" as an error and set ec, but the other one not treat it as an error?

    For both functions, a non-existent file is not an error. Both functions return true if the file was removed successfully, return false if it didn't exist, and report an error (by throwing or setting ec) if an error occurred, (possible errors include a failure when checking whether the file exists, or failure to remove the file). The behaviour of the two overloads is consistent.

    When an error is reported by throwing an exception, obviously there is no return value. When an error is reported by setting ec, the function still has to return something. The last sentence "The signature with argument ec returns false if an error occurs." is telling you what is returned in that case. It's not telling you that returning false always implies an error occurred.

    Or put another way, it says that when an error occurs, it returns false. That's not the same as saying that when it returns false, that means an error occurred.