util: Add util function to remove an entire directory tree (dangerous?).

This commit is contained in:
Adam Sutton 2012-11-02 16:32:28 +00:00
parent 6254fb5622
commit 41f1c671f0
2 changed files with 32 additions and 0 deletions

View file

@ -482,6 +482,8 @@ char *md5sum ( const char *str );
int makedirs ( const char *path, int mode );
int rmtree ( const char *path );
/* printing */
#if __SIZEOF_LONG__ == 8
#define PRItime_t PRId64

View file

@ -22,6 +22,9 @@
#include <assert.h>
#include <openssl/md5.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include "tvheadend.h"
/**
@ -373,3 +376,30 @@ makedirs ( const char *inpath, int mode )
}
return 0;
}
int
rmtree ( const char *path )
{
int err;
struct dirent de, *der;
struct stat st;
char buf[512];
DIR *dir = opendir(path);
if (!dir) return -1;
while (!readdir_r(dir, &de, &der) && der) {
if (!strcmp("..", de.d_name) || !strcmp(".", de.d_name))
continue;
snprintf(buf, sizeof(buf), "%s/%s", path, de.d_name);
err = stat(buf, &st);
if (err) break;
if (S_ISDIR(st.st_mode))
err = rmtree(buf);
else
err = unlink(buf);
if (err) break;
}
closedir(dir);
if (!err)
err = rmdir(path);
return err;
}