"Fossies" - the Fresh Open Source Software archive

Member "LVM/1.0.8/tools/lib/lvm_remove_recursive.c" of archive lvm_1.0.8.tar.gz:


/*
 * Copyright (C)  1998, 1999  Heinz Mauelshagen, Sistina Software
 *
 * February 2000
 *
 * This LVM library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This LVM library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this LVM library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA
 *
 */

#include <liblvm.h>


int lvm_remove_recursive ( const char *dir) {
   int ret = 0;
   int size;
   char *file_name = NULL;
   struct stat sb;
   struct dirent *dir_ent = NULL;
   DIR *this_dir = NULL;

   debug_enter ( "lvm_remove_recursive -- CALLED with dir: %s\n", dir);

   if ( dir != NULL) {
      if ( lstat ( dir, &sb) == 0) {
         /* check beeing called with a file name */
         if (  !S_ISDIR ( sb.st_mode)) unlink ( dir);
         else {
            /* open and read the directory */
            if ( ( this_dir = opendir ( dir)) != NULL) {
               while ( ( dir_ent = readdir ( this_dir)) != NULL && ret == 0) {
                  if ( strcmp ( dir_ent->d_name,".") == 0 ||
                       strcmp ( dir_ent->d_name,"..") == 0) continue;
                  size = strlen (dir) + strlen (dir_ent->d_name) + 3;
                  if ( ( file_name = malloc ( size)) == NULL) {
                     ret = -LVM_EREMOVE_RECURSIVE_MALLOC;
                     goto lvm_remove_recursive_end;
                  }
                  memset ( file_name, 0, size);
                  snprintf ( file_name, size - 1,
                                        "%s/%s", dir, dir_ent->d_name);
                  if ( lstat ( file_name, &sb) == 0) {
                     if ( S_ISDIR ( sb.st_mode)) {
                         if ( ( ret = lvm_remove_recursive ( file_name)) == 0)
                            rmdir ( file_name);
                     } else unlink ( file_name);
                  }
                  free ( file_name);
               }
               closedir ( this_dir);
               rmdir ( dir);
            } else ret = -LVM_EREMOVE_RECURSIVE_OPENDIR;
         }
      }
   }

lvm_remove_recursive_end:

   debug_leave ( "lvm_remove_recursive -- LEAVING with ret: %d\n", ret);
   return ret;
}