remove.c

Go to the documentation of this file.
00001 /***********************************************************************
00002  *
00003  *  G_remove (element, name)
00004  *     char *element          mapset element containing name
00005  *     char *name             file name to be removed
00006  *
00007  *  Only files in current mapset can be removed
00008  *
00009  *  Returns  -1  on fail
00010  *            0  if no file
00011  *            1  if successful
00012  *
00013  ***********************************************************************/
00014 
00015 #include <stdio.h>
00016 #include <string.h>
00017 #include <unistd.h>
00018 #include <stdlib.h>
00019 #include <sys/types.h>
00020 #include <sys/stat.h>
00021 #include <dirent.h>
00022 #include <grass/gis.h>
00023 
00024 #ifdef __MINGW32__
00025 #define lstat(path, sb) stat(path, sb)
00026 #endif
00027 
00028 static int recursive_remove(const char *path);
00029 
00045 int G_remove ( char *element, char *name)
00046 {
00047     char path[1024];
00048     char *mapset;
00049     char xname[512], xmapset[512];
00050 
00051     if (G_legal_filename(name) < 0)
00052             return -1;
00053 
00054 /* name in mapset legal only if mapset is current mapset */
00055     mapset = G_mapset();
00056     if (G__name_is_fully_qualified (name, xname, xmapset)
00057     && strcmp (mapset, xmapset))
00058             return -1;
00059 
00060 /* if file does not exist, return 0 */
00061     if (access (G__file_name (path, element, name, mapset),0) != 0)
00062             return 0;
00063 
00064     if (recursive_remove(path) == 0)
00065             return 1;
00066 
00067     return -1;
00068 }
00069 
00070 /* equivalent to rm -rf path */
00071 static int
00072 recursive_remove(const char *path)
00073 {
00074         DIR *dirp;
00075         struct dirent *dp;
00076         struct stat sb;
00077         char path2[4096];
00078 
00079         if(lstat(path, &sb))
00080                 return 1;
00081         if(!S_ISDIR(sb.st_mode))
00082                 return remove(path) == 0 ? 0 : 1;
00083 
00084         if((dirp = opendir(path)) == NULL)
00085                 return 1;
00086         while((dp = readdir(dirp)) != NULL)
00087         {
00088                 if(dp->d_name[0] == '.')
00089                         continue;
00090                 if (strlen(path) + strlen(dp->d_name) + 2 > sizeof(path2))
00091                         continue;
00092                 sprintf(path2, "%s/%s", path, dp->d_name);
00093                 recursive_remove(path2);
00094         }
00095         closedir(dirp);
00096 
00097         return rmdir(path) == 0 ? 0 : 1;
00098 }

Generated on Wed Dec 19 14:59:06 2007 for GRASS by  doxygen 1.5.4