[Windows]_[刪除非空檔案夾的注意要點]

來源:互聯網
上載者:User

標籤:不能   需求   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]_[刪除非空檔案夾的注意要點]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.