Delete a directory recursively – Linux sample program

September 5th, 2008  |  Published in Linux Sample Programs  |  6 Comments








// Author : Amit Sahrawat

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>
 

#ifdef DEBUG
#define TRC_SYSMNGR printf
#else
#define TRC_SYSMNGR 
#endif

#include <dirent.h>

int deletepath(char *path)
{

 struct dirent *d = NULL;

DIR *dir = NULL; /* pointer to directory head*/

char buf[64]={0}; /* buffer to store the complete file/dir name*/

struct stat statbuf; /* to obtain the statistics of file/dir */

int retval =0; /* to hold the return value*/

 

memset(&statbuf,0,sizeof(struct stat)); 

retval = stat(path,&statbuf);

TRC_SYSMNGR(“deletepath : PATH : %s\n”,path);

/* if the stat returned success and path provided is of valid directory*/

if(S_ISDIR(statbuf.st_mode) && (retval==0))

{

dir = opendir(path); /* open the directory*/

/* reads entry one by one*/

while(d = readdir(dir))

{

TRC_SYSMNGR(“D_Name : %s\n”,d->d_name);

if((strcmp(d->d_name,”.”)!=0) && (strcmp(d->d_name,”..”)!=0))

{

sprintf(buf,”%s/%s”,path,d->d_name);

retval = stat(buf,&statbuf);

if(retval == 0)

{

TRC_SYSMNGR(“Mode : 0x%x\n”,statbuf.st_mode);

if(!S_ISDIR(statbuf.st_mode))

{

/* This is file, remove the entry*/

TRC_SYSMNGR(“Is File\n”);

remove(buf);

}

else

{

/*

  This is a directory, recursive search in it

  once all files are removed, delete the directory

*/

TRC_SYSMNGR(“Is Dir\n”);

deletepath(buf);

remove(buf);

}

}

else

{

perror(“stat failed\n”);

}

}

}

/* Now remove the head directory provided, as it empty now*/

remove(path);

}

else

{

perror(“Failed”);

}

TRC_SYSMNGR(“Retval : %d\n”,retval);

return retval;

}
// For Testing 
int main()
{ 

deletepath(“recur/testdir”); // Test path for directory

return 0;

}

Compilation:
gcc deletepath.c -o del -DDEBUG

Subscribe

Get articles in your inbox.

Enter your email address:

Join Us

Twitter Chatter


Recommendations

Archives

Categories