diff options
author | Adam Spragg <adam@spra.gg> | 2022-12-07 20:05:32 +0000 |
---|---|---|
committer | Adam Spragg <adam@spra.gg> | 2022-12-07 20:05:32 +0000 |
commit | a7096903fdf611a58466946456587820696bc62f (patch) | |
tree | fe49395de891deca2e56814ec1cbd07c043cc2b7 | |
parent | 302e325770f749180c8c95297eb6dff53cc9d8ab (diff) |
Solve puzzle 7 part 2
-rw-r--r-- | 7.c | 48 |
1 files changed, 40 insertions, 8 deletions
@@ -4,6 +4,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> //#define DENT_DUMP @@ -266,13 +267,24 @@ cmd_cd(struct dent ** cwd, char * buf, size_t bufsiz, FILE * in, char const * ar int -main() +main(int argc, char ** argv) { char buf[BUFSIZ]; struct dent * cwd = NULL, * root, * d; - int i; + int i, part = 1; size_t s; + while ((i = getopt(argc, argv, "p:")) != -1) { + switch (i) { + case 'p': + part = atoi(optarg); + break; + + default: + return -1; + } + } + i = fgets(buf, sizeof(buf), stdin) ? 0 : -1; while (i == 0) { char * tok, * toksave = NULL; @@ -316,13 +328,33 @@ main() // Calculate disk usage sizes; dent_du(root); - // Find directories whose size is less than a limit, and sum them. - s = 0; - for (d = root; d != NULL; d = dent_next(d)) { - if (d->type == DT_DIR && d->size <= 100000) - s += d->size; + switch (part) { + case 1: + // Find directories whose size is less than a limit, and sum them. + s = 0; + for (d = root; d != NULL; d = dent_next(d)) { + if (d->type == DT_DIR && d->size <= 100000) + s += d->size; + } + printf("Sum of dir sizes where size <= 100000: %zu\n", s); + break; + + case 2: + // Find smallest directory to delete that drops disk space to 70M - 30M + s = 70000000; + for (d = root; d != NULL; d = dent_next(d)) { + if (d->type == DT_DIR + && d->size < s + && root->size - d->size < 40000000) + s = d->size; + } + printf("Smallest dir that can drop usage below 40000000: %zu\n", s); + break; + + default: + fprintf(stderr, "Unexpected part %d\n", part); + return -1; } - printf("Sum of dir sizes where size <= 100000: %zu\n", s); // Tidy up dent_free(root); |