How to delete a folder in C++?

后端 未结 16 1365
悲&欢浪女
悲&欢浪女 2020-12-03 00:45

How can I delete a folder using C++?

If no cross-platform way exists, then how to do it for the most-popular OSes - Windows, Linux, Mac, iOS, Android? Would a POSIX

16条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 01:31

    With C++17 you can use std::filesystem, in C++14 std::experimental::filesystem is already available. Both allow the usage of filesystem::remove().

    C++17:

    #include 
    std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
    std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
    

    C++14:

    #include 
    std::experimental::filesystem::remove("myDirectory");
    

    Note 1: Those functions throw filesystem_error in case of errors. If you want to avoid catching exceptions, use the overloaded variants with std::error_code as second parameter. E.g.

    std::error_code errorCode;
    if (!std::filesystem::remove("myEmptyDirectoryOrFile", errorCode)) {
        std::cout << errorCode.message() << std::endl;
    }
    

    Note 2: The conversion to std::filesystem::path happens implicit from different encodings, so you can pass strings to filesystem::remove().

提交回复
热议问题