標籤:不能 需求 opera pac unicode hwnd 長度 儲存 釋放
情境:
1. 有時候程式須要產生一些暫時檔案夾和暫時檔案,在程式退出時須要刪除,這時候用win32的api就可以完畢需求。自己遍曆檔案夾一個個removefile並非高效率的做法.
//注意://1.要刪除的檔案夾不能以\\結尾.僅僅能以檔案夾名結尾。比方C:\\New Folder,而不是C:\\New Folder\\,不然會失敗.能夠使用/作為分隔字元.//2.pFrom的值必須是以\0結尾的字串,unicode字串要以兩個\0\0結尾.//3.能夠使用std::string或std::wstring的c_str(),由於這個函數返回的字串已經帶\0或\0\0結尾.//4.要刪除的檔案夾裡的檔案或檔案夾的控制代碼必須被釋放,假設有佔用的控制代碼。刪除會失敗.//5.FOF_SILENT 是設定不出現進度條表單.//6.FOF_NOCONFIRMATION 是不彈出確認對話方塊.
test_deletedir.cpp 注意,檔案以utf8格式儲存.
#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);//返回須要的unicode長度 WCHAR * wszUNICODE = new WCHAR[nLen+1]; memset(wszUNICODE, 0, nLen * 2 + 2); nLen = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)utf8, -1, wszUNICODE, nLen); //把utf8轉成unicodereturn wszUNICODE;}int main(int argc, char const *argv[]){wchar_t* unicode = ConvertUtf8ToUnicode("C:\\Users\\apple\\Desktop\\建立檔案夾");int res = WXDeleteDir(unicode);cout << "res: " << res << endl; assert(!res);free(unicode);return 0;}
[Windows]_[刪除非空檔案夾的注意要點]