C Language implementation of Linux Delete non-empty directory

Source: Internet
Author: User
Tags strcmp

#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.