X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=blobdiff_plain;f=dus.c;h=536d60723d32492b0a03da338265be9850fd75a9;hb=5e8a9db72b7db4795cbbc77e562454919c603993;hp=d1774df032335764c9d9c3c6b943a4b039b02e28;hpb=3701b8b8ca9af54aabb8c5b8757ee1ec17ae063a;p=dus.git diff --git a/dus.c b/dus.c index d1774df..536d607 100644 --- a/dus.c +++ b/dus.c @@ -33,12 +33,6 @@ #include #include -struct file_with_size { - char *filename; - size_t size; - struct file_with_size *next; -}; - size_t file_or_dir_size(char *name) { DIR *dir; struct dirent *dir_e; @@ -77,6 +71,14 @@ size_t file_or_dir_size(char *name) { return result; } +/**********************************************************************/ + +struct file_with_size { + char *filename; + size_t size; + struct file_with_size *next; +}; + struct file_with_size *create(char *name, struct file_with_size *current) { struct file_with_size *result; result = malloc(sizeof(struct file_with_size)); @@ -86,6 +88,62 @@ struct file_with_size *create(char *name, struct file_with_size *current) { return result; } +void destroy(struct file_with_size *node) { + struct file_with_size *next; + while(node) { + next = node->next; + free(node->filename); + free(node); + node = next; + } +} + +/**********************************************************************/ + +int compare_files(const void *x1, const void *x2) { + const struct file_with_size **f1, **f2; + + f1 = (const struct file_with_size **) x1; + f2 = (const struct file_with_size **) x2; + + if((*f1)->size < (*f2)->size) { + return -1; + } else if((*f1)->size > (*f2)->size) { + return 1; + } else { + return 0; + } +} + + +void print_sorted(struct file_with_size *root) { + struct file_with_size *node; + struct file_with_size **nodes; + int nb, n; + + nb = 0; + for(node = root; node; node = node->next) { + nb++; + } + + nodes = malloc(nb * sizeof(struct file_with_size *)); + + n = 0; + for(node = root; node; node = node->next) { + nodes[n++] = node; + } + + qsort(nodes, nb, sizeof(struct file_with_size *), compare_files); + + for(n = 0; n < nb; n++) { + printf("%u %s\n", nodes[n]->size, nodes[n]->filename); + } + + free(nodes); +} + +/**********************************************************************/ + int main(int argc, char **argv) { int k; struct file_with_size *root; @@ -95,12 +153,9 @@ int main(int argc, char **argv) { root = create(argv[k], root); } - while(root) { - printf("%u %s\n", - root->size, - root->filename); - root = root->next; - } + print_sorted(root); + + destroy(root); exit(0); }