標籤:shfileoperation 刪除目錄 delete remove win32
情境:
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
#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]_[刪除非空目錄的注意要點]