/* prsize2.c James S. Plank Fall, 1996 CS360 Latest tweaks to keep it up to date: February, 2021. */ /* This prepares for recursion by bundling up the functionality in a procedure called get_size(). */ #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); } else { total_size += buf.st_size; } } /* Now the closedir call feels necessary*/ closedir(d); return total_size; } int main() { long total_size; total_size = get_size("."); printf("%ld\n", total_size); return 0; }