empty-dirs

Find empty directories
git clone git://bvnf.space/empty-dirs.git
Log | Files | Refs | README

empty-dirs.c (1025B)


      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int
dfs(char *path) {
	struct dirent *dp;
	int dfd, i;
	DIR *d = opendir(path);
	if (d == NULL) {
		perror(path);
		return 1;
	}

	dfd = dirfd(d);

	i = 0;
	while ((dp = readdir(d)) != NULL) {
		struct stat sb;

		if (strcmp(dp->d_name, ".") == 0 ||
				strcmp(dp->d_name, "..") == 0)
			continue;

		i++;

		fstatat(dfd, dp->d_name, &sb, 0);
		if (S_ISDIR(sb.st_mode)) {
			char *fullpath = calloc(1, strlen(path) + strlen(dp->d_name) + 2);
			if (fullpath == NULL) {
				perror("calloc");
				exit(1);
			}

			strcat(fullpath, path);
			strcat(fullpath, "/");
			strcat(fullpath, dp->d_name);

			dfs(fullpath);
			free(fullpath);
		}
	}
	if (i == 0)
		printf("%s\n", path);

	closedir(d);

	return 0;
}

int
main(int argc, char **argv) {
	if (argc == 1) {
		fprintf(stderr, "usage: %s dir...\n", argv[0]);
		return 1;
	}

    while (*(++argv)) {
		dfs(*argv);
    }

	return 0;
}