C语言实现递归删除文件夹及文件

 

  // 实现递归删除文件及文件夹 // 该程序不能删除只读文件 #include <stdio.h> #include <stdlib.h> #include <direct.h> #include <conio.h> #include <io.h> #include <string.h> #include <sys/stat.h> #define MAXPATH 256 //========================================================= int Create(const char * rootpath) { struct _finddata_t fileinfo; struct _stat buf; long result ; char* filename; // 文件名 char filepath[MAXPATH]; // 带通配符文件夹的路径名 char* str1; // 通配符字符串"*.*" char path[MAXPATH]; // 临时存储的路径 char ch; // 用于获取到"."的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 */

 

你可能感兴趣的:(c,struct,File,存储,语言,Path)