[Windows]_[删除非空目录的注意要点]

来源:互联网 发布:个体工商户开淘宝 编辑:程序博客网 时间:2024/05/16 13:06


场景:

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;}


0 0
原创粉丝点击