#include #include #include /* for unix system interfaces calls */ #include /* for O_RDONLY and such */ #include /* for the stat() function and struct stat*/ #include /* for dev_t, S_IFMT et al */ #include /* portable interface to implementation specifics */ #define MAX_PATH 1024 void fsize(char*); void dirwalk(char *, void (*fcn)(char *)); /* print file sizes */ int main(int argc, char *argv[]) { if (argc == 1) fsize("."); else while (--argc > 0) fsize(*++argv); return 0; } /* fsize: print size of file "name" */ void fsize(char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "fsize: can't access %s\n", name); return; } if ((stbuf.st_mode & S_IFMT) == S_IFDIR) dirwalk(name, fsize); printf("%8ld %s %8d:%d -- %d\n", stbuf.st_size, name, stbuf.st_uid, stbuf.st_gid, (int) stbuf.st_atime); } /* dirwalk: apply fcn to all files in dir */ void dirwalk(char *dir, void (*fcn)(char *)) { char name[MAX_PATH]; struct dirent *dp; DIR *dfd; if ((dfd = opendir(dir)) == NULL) { fprintf(stderr, "dirwalk: can't open %s\n", dir); return; } while ((dp = readdir(dfd)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) continue; if (strlen(dir)+strlen(dp->d_name)+2 > sizeof(name)) fprintf(stderr, "dirwalk: name %s/%s too long\n", dir, dp->d_name); else { sprintf(name, "%s/%s", dir, dp->d_name); (*fcn)(name); } } closedir(dfd); }