How to delete a folder in C++?

后端 未结 16 1287
悲&欢浪女
悲&欢浪女 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:30
    void remove_dir(char *path)
    {
            struct dirent *entry = NULL;
            DIR *dir = NULL;
            dir = opendir(path);
            while(entry = readdir(dir))
            {   
                    DIR *sub_dir = NULL;
                    FILE *file = NULL;
                    char abs_path[100] = {0};
                    if(*(entry->d_name) != '.')
                    {   
                            sprintf(abs_path, "%s/%s", path, entry->d_name);
                            if(sub_dir = opendir(abs_path))
                            {   
                                    closedir(sub_dir);
                                    remove_dir(abs_path);
                            }   
                            else 
                            {   
                                    if(file = fopen(abs_path, "r"))
                                    {   
                                            fclose(file);
                                            remove(abs_path);
                                    }   
                            }   
                    }   
            }   
            remove(path);
    }
    
    0 讨论(0)
  • 2020-12-03 01:30

    //For windows:

    #include <direct.h>
    
    
    if(_rmdir("FILEPATHHERE") != -1)
    {
      //success     
    } else {
      //failure
    }
    
    0 讨论(0)
  • 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 <filesystem>
    std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
    std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
    

    C++14:

    #include <experimental/filesystem>
    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().

    0 讨论(0)
  • 2020-12-03 01:31

    The directory should be empty.

    BOOL RemoveDirectory( LPCTSTR lpPathName );
    
    0 讨论(0)
提交回复
热议问题