Scene:
1. Sometimes the program needs to generate some temporary folders and temporary files, when the program exits need to delete, this time with the Win32 API can complete the requirements. Traversing folders by themselves RemoveFile is not an efficient practice.
Note://1. The folder you want to delete cannot end with \ \. You can only end with a folder name. For example, C:\\new Folder, not c:\\new folder\\, will fail. Ability to use/as a delimiter. The value of//2.pfrom must be a string terminated with a, Unicode string ending with two \0\0.//3. Able to use std:: String or std::wstring of C_str (), because the function returned by this functions has been terminated with a/\0\0.//4. The handle to the file or folder in the folder to be deleted must be disposed, assuming there is a handle occupied. The delete will fail.//5.fof_silent is the setting does not appear in the progress bar form.//6.fof_noconfirmation is not popup confirmation dialog box.
Test_deletedir.cpp Note that the files are stored in UTF8 format.
#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 points for windows]_[deleting non-empty folders]