/* * q2.c - display the size in bytes of the largest file in each directory * specified as command-line argument. * * Alan J Rosenthal, October 2000. */ #include #include #include #include #include int main(int argc, char **argv) { DIR *dp; struct dirent *p; int i, status = 0, len; long max; char buf[200]; struct stat statbuf; for (i = 1; i < argc; i++) { if ((len = strlen(argv[i])) + 2 > sizeof buf) { fprintf(stderr, "%s: directory name too long\n", argv[i]); status++; } else if ((dp = opendir(argv[i])) == NULL) { perror(argv[i]); status++; } else { sprintf(buf, "%s/", argv[i]); len++; /* now buf[len] is the first byte after that slash */ max = 0; while ((p = readdir(dp))) { if (strlen(p->d_name) + len + 1 > sizeof buf) { buf[len] = '\0'; fprintf(stderr, "%s%s: filename too long\n", buf, p->d_name); /* * use status=1 instead of status++ in case we have a lot * of these */ status = 1; } else { strcpy(buf + len, p->d_name); /* a concatenation */ if (stat(buf, &statbuf)) { perror(buf); status++; } else if (statbuf.st_size > max) { max = statbuf.st_size; } } } closedir(dp); printf("%s: %ld\n", argv[i], max); } } return(status); }