您的位置:首页 > 编程语言 > C语言/C++

C++ 递归方式删除非空目录文件夹

2013-04-10 19:28 204 查看
#include
<string>

#include <queue>

#include <stack>


#include <iostream>


#include <Windows.h>

/////////////////

#include <stdlib.h>

#include <direct.h>

#include <string.h>

#include <io.h>

#include <stdio.h>

#include <iostream>

#include <conio.h>

#include <process.h>

#include <windows.h>


using namespace std;


方式一:

int delDir(const
char
* pDir)

{

if (NULL == pDir)	return -1;


char dir[MAX_PATH] = {0};

char fileName[MAX_PATH] = {0};


char *str = "\\*.*";

strcpy(dir,pDir);

strcat(dir,str);


//首先查找dir中符合要求的文件

long hFile;

_finddata_t fileinfo;

if ((hFile = _findfirst(dir,&fileinfo)) != -1)

{

do

{

strcpy(fileName,pDir);

strcat(fileName,"\\");

strcat(fileName,fileinfo.name);

//检查是不是目录

//如果不是目录,则进行处理文件夹下面的文件

if (!(fileinfo.attrib & _A_SUBDIR))

{

remove(fileName);

}

else//处理目录,递归调用

{

if ( strcmp(fileinfo.name, "." ) != 0 && strcmp(fileinfo.name, ".." ) != 0 )

{

delDir(fileName);

//rmdir(fileName);

}

}

} while (_findnext(hFile,&fileinfo) == 0);

_findclose(hFile);

rmdir(pDir);

return 1;

}

return -3;

}

方式二:

void myRmDir(
wstring
sRmDir )

{

//wchar_t wPath[MAX_PATH] = {0};

//wcstombs(path,wPath,MAX_PATH);//将宽字符转换成多字符

//mbstowcs(wPath,pDir,strlen(pDir));//把多字符把转换成宽字符


queue<wstring> DirQueue; // 用于删除文件

stack<wstring> DirStack; // 用于删除目录


if ( sRmDir.at( sRmDir.length() -1 ) != '\\' ||

sRmDir.at( sRmDir.length() -1 ) != '/' )

{

sRmDir += L"\\";

}


DirQueue.push( sRmDir );

DirStack.push( sRmDir );


//循环删除 目录中的文件

while ( !DirQueue.empty() )

{

wstring sFindDir;

sFindDir = DirQueue.front();

DirQueue.pop();


wstring sFindFirstFile;

sFindFirstFile = sFindDir;

sFindFirstFile += L"*";


HANDLE hFind = INVALID_HANDLE_VALUE;

WIN32_FIND_DATA Win32FindData;

hFind = FindFirstFile( sFindFirstFile.c_str(), &Win32FindData );


do

{

if ( hFind == INVALID_HANDLE_VALUE )

{

break;

}

else

{

wstring sFindFile;

sFindFile = sFindDir;

sFindFile += Win32FindData.cFileName;


if ( Win32FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )

{

if ( wcscmp( Win32FindData.cFileName, L"." ) != 0 && wcscmp( Win32FindData.cFileName, L".." ) != 0 )

{

sFindFile += L"\\";

DirQueue.push( sFindFile );

DirStack.push( sFindFile );

}

}

    else

{

DeleteFile( sFindFile.c_str() );

}

}


} while ( FindNextFile( hFind, &Win32FindData ) );


if ( hFind != INVALID_HANDLE_VALUE )

{

FindClose( hFind );

hFind = INVALID_HANDLE_VALUE;

}

}


//删除目录

while ( !DirStack.empty() )

{

wstring sDir;

sDir = DirStack.top();

DirStack.pop();


RemoveDirectory( sDir.c_str() );

}

}

int main(int
argc,
char*
argv[])

{

char szDir[ MAX_PATH ] = { 0 };

bool bRet = false;


std::cout << "please wait ...";


    myRmDir( L"d:\\v" );
delDir("D:\\project.KeyManagerClient - 副本");


std::cout << "ok";


return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: