c++filesystemsis-emptydelete-directory

What is std::filesystem::remove_all() supposed to do with an empty path?


I wonder, what is supposed to happen with a call such as this?

#include <filesystem>

int main() {
    std::filesystem::remove_all({});
    return 0;
}

I guess path::empty() implies that my argument is an empty path, but this page does not have anything that I recognize as useful regarding empty paths.


Solution

  • Normal form of an empty path is an empty path. It is represented by "" (empty string) in the literal sense. And an empty path doesn’t exist as a real path on the filesystem of the OS. You can test this with:

    std::filesystem::exists(std::filesystem::path{}); /* <—- will return false */
    

    The program code in the OP

    #include <filesystem>
    
    int main() {
        std::filesystem::remove_all({});
        return 0;
    }
    

    Will therefore be expected to behave according to the specification in the standard:

    Remove all

    uintmax_t remove_all(const path& p);
    uintmax_t remove_all(const path& p, error_code& ec);
    1. Effects: Recursively deletes the contents of p if it exists, then deletes file p itself, as if by POSIX remove(). [Note: A symbolic link is itself removed, rather than the file it resolves to. —end note]

    2. Postconditions: exists(symlink_status(p)) is false.

    3. Returns: The number of files removed. The signature with argument ec returns static_cast<uintmax_t>(-1) if an error occurs.

    —-ISO/IEC JTC1 SC22 WG21 N4860 29.11.14.31

    Since std::filesystem::path{} doesn’t exist on the OS, the return value of

    std::filesystem::remove_all({});
    

    Will be 0. No files will be removed.