Listing 7 Deletes a directory tree

/* ddir.c: Remove directory tree */

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>

/* All POSIX-compliant systems have this one */
#include <dirent.h>

/* Borland C also requires this one */
#include <dir.h>

/* This is required to redirect stderr on DOS */
#include "stderr.h"

/* DOS-specific macros - change for other OS */
#define CMD_FORMAT "del *.* <%s > nul"
#define CMD_LEN 17

/* Change this to "/" for UNIX */
char Response_file[L_tmpnam+1] = "\\";

void rd(char *);
main(int argc, char **argv)
{
   FILE *f;
   char *old_path = getcwd(NULL,FILENAME_MAX);

   /* Create response file for DOS del command */
   tmpnam(Response_file+1);
   assert((f = fopen(Response_file,"w")) != NULL);
   fputs("Y\n",f);
   fclose(f);

   /* Delete the directories */
   while (--argc)
      rd(*++argv);

   /* Clean-up */
   remove(Response_file);
   chdir(old_path);
   free(old_path);
   return 0;
}

void rd(char * dir)
{
   char sh_cmd[L_tmpnam+CMD_LEN];
   DIR *dirp;
   struct dirent *entry;
   struct stat finfo;

   /* Log onto the directory that is to be deleted */
   assert(chdir(dir) == 0);
   printf("%s:\n",strlwr(dir));

   /* Delete all normal files via OS shell */
   hide_stderr();
   sprintf(sh_cmd,CMD_FORMAT,Response_file);
   system(sh_cmd);
   restore_stderr();

   /* Delete any remaining directory entries */
   assert((dirp = opendir(".")) != NULL);
   while ((entry = readdir(dirp)) != NULL)
   {
      if (entry->d_name[0] == '.')
         continue;
      stat(entry->d_name,&finfo);
      if (finfo.st_mode & S_IFDIR)
         rd(entry->d_name);    /* Subdirectory */
      else
      {
         /* Enable delete of file, then do it */
         chmod(entry->d_name,S_IWRITE);
         assert(unlink(entry->d_name) == 0);
      }
   }
   closedir(dirp);

   /* Remove the directory from its parent */
   assert(chdir("..") == 0);
   assert(rmdir(dir) == 0);
}

/* End of File */