Advertisement
Tavi33

SO #5

Oct 25th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <dirent.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <unistd.h>
  10.  
  11. int deleteDirectoryContent(char* path) {
  12.   struct dirent *entry;
  13.   DIR* dir = opendir(path);
  14.   int count=0;
  15.   if(dir) {
  16.     while(entry = readdir(dir)) {
  17.       if(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
  18.     struct stat st;
  19.     char* entryPath = (char *) malloc((sizeof(entry->d_name)+sizeof(path))*sizeof(char));
  20.     strcpy(entryPath, path);
  21.     strcat(entryPath, "/");
  22.     strcat(entryPath, entry->d_name);
  23.     lstat(entryPath, &st);
  24.     if(S_ISLNK(st.st_mode)) {
  25.       int bufsize = st.st_size + 1;
  26.       char* buf = malloc(bufsize);
  27.       struct stat lst;
  28.       readlink(entryPath, buf, bufsize);
  29.       lstat(buf, &lst);
  30.       if((lst.st_mode & S_IROTH) == 0) {
  31.         count++;
  32.       }
  33.     } else if(S_ISDIR(st.st_mode)) {
  34.       count += deleteDirectoryContent(entryPath);
  35.     } else if(S_ISREG(st.st_mode)) {
  36.       if((st.st_mode & S_IROTH) == 0) {
  37.         remove(entryPath);
  38.         printf("Deleted entry %s in %s\n", entry->d_name, path);
  39.       }
  40.      
  41.     }
  42.       }
  43.      
  44.     }
  45.   }
  46.   closedir(dir);
  47.   return count;
  48.  
  49. }
  50.  
  51. int main(int argc, char *args[]) {
  52.   if(argc != 2) {
  53.     fprintf(stderr, "Usage: %s <directory>\n", args[0]);
  54.     exit(1);
  55.   }
  56.   struct stat st;
  57.   stat(args[1], &st);
  58.   if(!S_ISDIR(st.st_mode)) {
  59.     fprintf(stderr, "%s is not a directory\n", args[1]);
  60.     exit(1);
  61.   }
  62.   int symbolicLinksCount = deleteDirectoryContent(args[1]);
  63.   printf("Number of files pointed to by symbolic links, without READ permission while deleteing: %d\n", symbolicLinksCount);
  64.   printf("Finished\n");
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement