// 实现递归删除文件及文件夹
// 该程序不能删除只读文件
#include
#include
#include
#include
#include
#include
#include
#define MAXPATH 256
//=========================================================
int Create(const char * rootpath)
{
struct _finddata_t fileinfo;
struct _stat buf;
longresult ;
char*filename;// 文件名
charfilepath[MAXPATH];// 带通配符文件夹的路径名
char*str1;// 通配符字符串"*.*"
charpath[MAXPATH];// 临时存储的路径
charch;// 用于获取到"."的ASCII值
//char*rootpath = "D://aaa";
str1 = "//*.*";
strcpy(filepath,rootpath);
strcat(filepath,str1);
//printf(" -> path: %s /n",filepath);
long hff = _findfirst( filepath,&fileinfo);
if( -1 == hff ){
printf( "filepath error/n" );
getchar();
exit(0);
}
do
{
strcpy(path,rootpath);
filename = fileinfo.name;
//printf(" %c ",*filename);
ch = *filename;
//printf(" %d ",ch);
if(ch == 46){// jump "." and ".." file
continue;
}
strcat(path,"//");
//printf("%s",path);
strcat(path,filename);
result = _stat( path, &buf );
//printf("-> name:%s | result:%ld | mode:%d/n", filename, result, buf.st_mode );
if( result != 0 )
{
perror( "$$$ Problem getting information" );
}
else
{
printf("-> %s ",path);
if( buf.st_mode == 16895 || buf.st_mode == 16749 )// Directory
{
printf("< DIR >/n");
Create(path);
if( _rmdir( path ) == 0 )
{
printf( "Directory '%s' was successfully removed/n" ,filename );
}
else
{
printf( "$$$ Problem removing directory '%s'/n" ,filename);
}
}
else if( buf.st_mode == 33206 || buf.st_mode == 33060 )// File
{
printf(" - file - /n");
if( remove( path ) == 0 )
{
printf("File %s was successfully removed./n",filename);
}
else
{
printf( "$$$ Problem removing File %s./n",filename );
}
}
else
{
printf("$$$ 'st_mode' ERROR! /n");
return -1;
}
}
}while( -1 != _findnext(hff,&fileinfo));
_findclose( hff );
return 0;
}
//=========================================================
int main(void)
{
const char * rootpath = "D://aaa";
Create(rootpath);
if( _rmdir( rootpath ) == 0 )
{
printf( "Directory '%s' was successfully removed/n" ,rootpath );
}
else
{
printf( "Problem removing directory '%s'/n" ,rootpath);
}
return 0;
}
//=========================================================
/* end of code */