• Main Page
  • Related Pages
  • Data Structures
  • Files
  • File List
  • Globals

remove.c

Go to the documentation of this file.
00001 
00017 #include <grass/config.h>
00018 #include <stdio.h>
00019 #include <string.h>
00020 #include <unistd.h>
00021 #include <stdlib.h>
00022 #include <sys/types.h>
00023 #include <sys/stat.h>
00024 #include <dirent.h>
00025 #include <grass/gis.h>
00026 
00027 static int recursive_remove(const char *path);
00028 static int G__remove(int misc, const char *dir, const char *element,
00029                      const char *name);
00030 
00047 int G_remove(const char *element, const char *name)
00048 {
00049     return G__remove(0, NULL, element, name);
00050 }
00051 
00067 int G_remove_misc(const char *dir, const char *element, const char *name)
00068 {
00069     return G__remove(1, dir, element, name);
00070 }
00071 
00072 static int G__remove(int misc, const char *dir, const char *element,
00073                      const char *name)
00074 {
00075     char path[GPATH_MAX];
00076     char *mapset;
00077     char xname[GNAME_MAX], xmapset[GMAPSET_MAX];
00078 
00079     /* name in mapset legal only if mapset is current mapset */
00080     mapset = G_mapset();
00081     if (G__name_is_fully_qualified(name, xname, xmapset)) {
00082         if (strcmp(mapset, xmapset) != 0)
00083             return -1;
00084         name = xname;
00085     }
00086 
00087     if (G_legal_filename(name) < 0)
00088         return -1;
00089 
00090     if (misc)
00091         G__file_name_misc(path, dir, element, name, mapset);
00092     else
00093         G__file_name(path, element, name, mapset);
00094 
00095     /* if file does not exist, return 0 */
00096     if (access(path, 0) != 0)
00097         return 0;
00098 
00099     if (recursive_remove(path) == 0)
00100         return 1;
00101 
00102     return -1;
00103 }
00104 
00105 /* equivalent to rm -rf path */
00106 static int recursive_remove(const char *path)
00107 {
00108     DIR *dirp;
00109     struct dirent *dp;
00110     struct stat sb;
00111     char path2[GPATH_MAX];
00112 
00113     if (G_lstat(path, &sb))
00114         return 1;
00115     if (!S_ISDIR(sb.st_mode))
00116         return remove(path) == 0 ? 0 : 1;
00117 
00118     if ((dirp = opendir(path)) == NULL)
00119         return 1;
00120     while ((dp = readdir(dirp)) != NULL) {
00121         if (dp->d_name[0] == '.')
00122             continue;
00123         if (strlen(path) + strlen(dp->d_name) + 2 > sizeof(path2))
00124             continue;
00125         sprintf(path2, "%s/%s", path, dp->d_name);
00126         recursive_remove(path2);
00127     }
00128     closedir(dirp);
00129 
00130     return rmdir(path) == 0 ? 0 : 1;
00131 }

Generated on Thu Dec 9 2010 20:46:05 for GRASS Programmer's Manual by  doxygen 1.7.2