zoukankan      html  css  js  c++  java
  • [Windows]_[删除非空文件夹的注意要点]


    场景:

    1. 有时候程序须要生成一些暂时文件夹和暂时文件,在程序退出时须要删除,这时候用win32的api就可以完毕需求。自己遍历文件夹一个个removefile并非高效率的做法.


    //注意:
    //1.要删除的文件夹不能以\结尾.仅仅能以文件夹名结尾。比方C:\New Folder,而不是C:\New Folder\,不然会失败.能够使用/作为分隔符.
    //2.pFrom的值必须是以结尾的字符串,unicode字符串要以两个结尾.
    //3.能够使用std::string或std::wstring的c_str(),由于这个函数返回的字符串已经带或结尾.
    //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转成unicode
    	return 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;
    }


  • 相关阅读:
    jenkins持续集成
    对pm2对研究
    模板⽅法模式
    python configparser模块
    Python正则表达式
    Python读写文件之换行符
    Python字符串
    Python字典
    Python列表
    爬虫 urllib,requests,lxml,bs4 小结
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6747547.html
Copyright © 2011-2022 走看看