How to delete a folder in C++?

后端 未结 16 1331
悲&欢浪女
悲&欢浪女 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:15

    For linux (I have fixed bugs in code above):

    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 new char[256];
                     if ((*(entry->d_name) != '.') || ((strlen(entry->d_name) > 1) && (entry->d_name[1] != '.')))
                    {   
                            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);
                                    }   
                            }   
                    }
                    delete[] abs_path;   
            }   
            remove(path);
    }
    

    For windows:

    void remove_dir(const wchar_t* folder)
    {
        std::wstring search_path = std::wstring(folder) + _T("/*.*");
        std::wstring s_p = std::wstring(folder) + _T("/");
        WIN32_FIND_DATA fd;
        HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
        if (hFind != INVALID_HANDLE_VALUE) {
            do {
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                    if (wcscmp(fd.cFileName, _T(".")) != 0 && wcscmp(fd.cFileName, _T("..")) != 0)
                    {
                        remove_dir((wchar_t*)(s_p + fd.cFileName).c_str());
                    }
                }
                else {
                    DeleteFile((s_p + fd.cFileName).c_str());
                }
            } while (::FindNextFile(hFind, &fd));
            ::FindClose(hFind);
            _wrmdir(folder);
        }
    }
    

提交回复
热议问题