#include <sys/stat.h>#include<dirent.h>#include<fcntl.h>/** * Recursively delete directories (delete the directory and the files and directories contained in the directory) * @dir: The absolute path of the directory to be deleted*/intRemove_dir (Const Char*dir) { CharCur_dir[] ="."; CharUp_dir[] =".."; Chardir_name[ -]; DIR*Dirp; structDirent *DP; structstat Dir_stat; //parameter passed in the directory does not exist, directly returned if(0!=Access (dir, F_OK)) { return 0; } //failed to get directory property, returned error if(0> Stat (dir, &Dir_stat)) {Perror ("Get directory Stat error"); return-1; } if(S_isreg (Dir_stat.st_mode)) {//Direct deletion of normal filesRemove (dir); } Else if(S_isdir (Dir_stat.st_mode)) {//directory files, recursively delete contents in directoryDIRP =Opendir (dir); while((Dp=readdir (DIRP))! =NULL) { //ignore. and. . if( (0= = strcmp (Cur_dir, dp->d_name)) | | (0= = strcmp (Up_dir, dp->d_name)) ) { Continue; } sprintf (Dir_name,"%s/%s", dir, dp->d_name); Remove_dir (Dir_name); //Recursive invocation} closedir (DIRP); RmDir (dir); //Delete Empty directory}Else{perror ("unknow file type!"); } return 0;}intMain () {stringDstpath ="/data/123"; //Delete directory if directory exists if(Access (DSTPATH.C_STR (),0) ==0) {cout<<"Remove"<< Dstpath <<Endl; intFlag =Remove_dir (Dstpath.c_str ()); cout<< Flag <<Endl; }}
C Language implementation of Linux Delete non-empty directory