/* * Make histogram showing distribution of filesizes in a directory. * * Command-line arguments: * directory path D * blocksize B * maximum number of blocks N * * Examines all the files in D and its subdirectories and prints * how many have size <= B, how many have size > B and <= 2*B, * etc., with the last category being files with size > N*B. */ #include #include #include #include #include /* * Main function. */ int main(int argc, char* argv[]) { int blocksize; int maxblocks; char * ending_char; /* for strtol error checking */ char * current_dir; int* hist; /* the histogram */ int i; /* parse command-line arguments */ if (argc < 4) { fprintf(stderr, "Usage: %s directorypath blocksize maxblocks\n", argv[0]); return EXIT_FAILURE; } blocksize = strtol(argv[2], &ending_char, 10); if ((*ending_char != '\0') || (blocksize <= 0)) { fprintf(stderr, "invalid blocksize\n"); return EXIT_FAILURE; } maxblocks = strtol(argv[3], &ending_char, 10); if ((*ending_char != '\0') || (maxblocks <= 0)) { fprintf(stderr, "invalid maxblocks\n"); return EXIT_FAILURE; } /* change to specified directory */ if (chdir(argv[1]) != 0) { fprintf(stderr, "Unable to access %s: %s\n", argv[1], strerror(errno)); return EXIT_FAILURE; } /* initialize histogram */ hist = malloc((maxblocks+1) * sizeof(int)); if (hist == NULL) { fprintf(stderr, "Not enough memory\n"); return EXIT_FAILURE; } for (i = 0; i < maxblocks+1; ++i) hist[i] = 0; /* YOUR CODE GOES HERE */ /* print results */ fprintf(stdout, "Results for directory %s with blocksize %d:\n\n", (current_dir = getcwd(NULL, 0)), blocksize); for (i = 0; i < maxblocks; ++i) { fprintf(stdout, "%20d files of size %10d blocks\n", hist[i], i+1); } fprintf(stdout, "%20d files of size %10d blocks or more\n", hist[maxblocks], maxblocks+1); free(current_dir); free(hist); return EXIT_SUCCESS; }