/* prsize3.c James S. Plank Fall, 1996 CS360 Latest tweaks to keep it up to date: February, 2021. */ /* This identifies directories and recursively calls get_size() on them. */ #include #include #include #include long get_size(const char *fn) { DIR *d; /* Return value of opendir(). */ struct dirent *de; /* Return value of each readdir() call. */ struct stat buf; /* The information about each file returned by stat() */ int exists; /* Return value of stat on each file. */ long total_size; /* The total size of all files. */ /* Initialize */ d = opendir(fn); if (d == NULL) { perror(fn); exit(1); } total_size = 0; /* Run through the directory and run stat() on each file, keeping track of the total size of all of the files. */ for (de = readdir(d); de != NULL; de = readdir(d)) { exists = stat(de->d_name, &buf); if (exists < 0) { fprintf(stderr, "Couldn't stat %s\n", de->d_name); exit(1); } total_size += buf.st_size; /* If the file is a directory, make a recursive call to get_size(): */ if (S_ISDIR(buf.st_mode)) { total_size += get_size(de->d_name); } } closedir(d); return total_size; } int main() { long total_size; total_size = get_size("."); printf("%ld\n", total_size); return 0; }