删除目录下所有子目录和文件

需求分析:

删除所给目录下所有子目录和文件

方法1:

递归删除目录下所有文件,将目录置成空目录,删除空目录

方法2:

POCO库(非递归方法)

方法1实现:

int  deleteDir(const char*  dirPath)
{
	vector vectPathLst;
	char path[250];
//制作路径  
	strcpy(path, dirPath);
	findFileInDir(path, "*", vectPathLst);
	vector::iterator iter = vectPathLst.end() - 1;
	string strPath = *iter;
	Poco::Path TmpPath = strPath;

	do{
		if (vectPathLst.size() <= 0){
			break;
		}
		if (iter == vectPathLst.end()){
			break;
		}
//是目录,继续搜索下一级目录,
		if (TmpPath.isDirectory()){
			deleteDir(strPath.c_str());
		}
		else{//是文件,删除文件
			remove(strPath.c_str());
		}
		vectPathLst.erase(iter);
	} while (true);
//删除子目录下所有文件后,删除目录
	remove(path);//删除空目录的方法 需修改
	return 0;
}
bool findFileInDir(const char* pchInDir, const char* pchFilter, vector & vecOutFileLst, bool bReturnPath)
{
	bool bFind = false;
	string strPath;
	strPath = pchInDir;
	try {
		Poco::DirectoryIterator it( strPath );
		Poco::DirectoryIterator end;
		if ( it == end )
			return bFind;
		if ( bReturnPath ) {
			strPath = pchInDir;
			if ( strPath[ strPath.length() - 1 ] != '/' )
			strPath += "/";
		} else
		strPath = "";
	string strOutFile;
//定义筛选条件
	vector vectStr;
	if ( pchFilter[ 0 ] == '*' )
		vectStr.push_back( "*" );
	GetVectStrFromStrWholeByChar( string( pchFilter ), '*', vectStr );
	if ( pchFilter[ strlen( pchFilter ) - 1 ] == '*' )
		vectStr.push_back( "*" );


	while ( it != end ) {
		if ( filterFile( vectStr, it.name().c_str() ) ) {
			if ( bReturnPath ) {
				strOutFile = strPath + it.name();
			} else
				strOutFile = it.name();
			vecOutFileLst.push_back( strOutFile );
			bFind = true;
		}
			it++;
		}
	} catch ( Poco::Exception& ex ) {
		logprintf( "Warn: findFileInDir( %s ) %s\n", strPath.c_str(), ex.message().c_str() );
	} catch ( ... ) {
		logprintf( "Warn: findFileInDir( %s )\n", strPath.c_str() );
	}
	return bFind;
}
// 1,2,3 ==> 1 2 3, NOTICE: Maybe need trimString first
size_t GetVectStrFromStrWholeByChar(const string& strWhole, const char chSep, vector& vectStr, bool bClean = true) 
{
	if (bClean)
		vectStr.clear() ; 
	if(strWhole.length() == 0) return 0 ; 
		string::size_type begPos=0, endPos ; // for string search
	while( (endPos=strWhole.find(chSep, begPos))  != string::npos) {
		string strSub = strWhole.substr(begPos, endPos-begPos) ;
		vectStr.push_back(strSub) ; 
		begPos = endPos+1 ; 
	}
	vectStr.push_back(strWhole.substr(begPos)) ; 
	return vectStr.size() ; 
}

方法2实现:

POCO库

Poco::File sFile( "D:\\AFCTFS" );//  D:\\AFCTFS为需要删除目录
sFile.remove( true ); //删除子目录和所有文件

参考:http://blog.csdn.net/blueln/article/details/8700299#userconsent#

你可能感兴趣的:(POCO)