Scene:
1. Sometimes the program needs to generate some temporary directory and temporary files, in the program exit need to delete, this time with the Win32 API can complete the requirements, traverse directory One by one removefile is not an efficient approach.
Note://1. The directory you want to delete cannot end with \ \. You can only end with a directory name, such as C:\\new Folder, not c:\\new folder\\, or it will fail. The value of//2.pfrom must be a string ending in. The Unicode string ends with two \0\0.//3. You can use the C_str () of std::string or std::wstring, because the string returned by this function has been terminated with either a or \0\0.//4. The handle to the file or directory in the directory to be deleted must be disposed, and if there is a handle occupied, the deletion will fail.//5.fof_silent is the setting does not appear in the Progress bar window.//6.fof_noconfirmation is not popup confirmation dialog box.
Test_deletedir.cpp
#define Unicode#include <windows.h> #include <iostream> #include <stdlib.h> #include <assert.h > Using namespace Std;int wxdeletedir (const wchar_t* path) {shfileopstruct fileop; Fileop.fflags = Fof_noconfirmation | Fof_silent; Fileop.hnamemappings = NULL; Fileop.hwnd = NULL; Fileop.lpszprogresstitle = NULL; Fileop.pfrom = path; Fileop.pto = NULL; Fileop.wfunc = Fo_delete; Return SHFileOperation (&FILEOP);} wchar_t* convertutf8tounicode (const char* UTF8) {if (!utf8) {wchar_t* buf = (wchar_t*) malloc (2); memset (buf,0,2); return BUF;} int nlen =:: MultiByteToWideChar (Cp_utf8,mb_err_invalid_chars, (LPCSTR) utf8,-1,null,0);//Returns the required Unicode length WCHAR * Wszunicode = new Wchar[nlen+1]; memset (wszunicode, 0, Nlen * 2 + 2); Nlen = MultiByteToWideChar (Cp_utf8, 0, (LPCSTR) UTF8,-1, Wszunicode, Nlen); Turn the UTF8 into Unicodereturn wszunicode;} int main (int argc, char const *argv[]) {wchar_t* unicode = Convertutf8tounicode ("c:\\users\\apple\\desktop\\ new Folder"); int res = Wxdeletedir (Unicode); cout << "Res:" << res << Endl; ASSERT (!res); free (Unicode); return 0;}
[Note on windows]_[Delete non-empty directory]