3 * dus is a simple utility designed to display the list of files and
4 * directories with disk occupancy, sorted according to it.
6 * Copyright (c) 2009 Francois Fleuret
7 * Written by Francois Fleuret <francois@fleuret.org>
9 * This file is part of dus.
11 * dus is free software: you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 3 as
13 * published by the Free Software Foundation.
15 * dus is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
18 * License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with dus. If not, see <http://www.gnu.org/licenses/>.
27 #include <sys/types.h>
36 size_t file_or_dir_size(char *name) {
45 if(lstat(name, &dummy) != 0) {
46 printf("Can not stat %s (%s).\n", name, strerror(errno));
50 if(S_ISLNK(dummy.st_mode)) {
57 while((dir_e = readdir(dir))) {
58 if(strcmp(dir_e->d_name, ".") &&
59 strcmp(dir_e->d_name, "..")) {
60 sprintf(subname, "%s/%s", name, dir_e->d_name);
61 result += file_or_dir_size(subname);
66 if(S_ISREG(dummy.st_mode)) {
67 result += dummy.st_size;
74 /**********************************************************************/
76 struct file_with_size {
79 struct file_with_size *next;
82 struct file_with_size *create(char *name, struct file_with_size *current) {
83 struct file_with_size *result;
84 result = malloc(sizeof(struct file_with_size));
85 result->filename = strdup(name);
86 result->size = file_or_dir_size(name);
87 result->next = current;
91 void destroy(struct file_with_size *node) {
92 struct file_with_size *next;
101 /**********************************************************************/
103 int compare_files(const void *x1, const void *x2) {
104 const struct file_with_size **f1, **f2;
106 f1 = (const struct file_with_size **) x1;
107 f2 = (const struct file_with_size **) x2;
109 if((*f1)->size < (*f2)->size) {
111 } else if((*f1)->size > (*f2)->size) {
119 void print_sorted(struct file_with_size *root) {
120 struct file_with_size *node;
121 struct file_with_size **nodes;
125 for(node = root; node; node = node->next) {
129 nodes = malloc(nb * sizeof(struct file_with_size *));
132 for(node = root; node; node = node->next) {
136 qsort(nodes, nb, sizeof(struct file_with_size *), compare_files);
138 for(n = 0; n < nb; n++) {
139 printf("%u %s\n", nodes[n]->size, nodes[n]->filename);
145 /**********************************************************************/
147 int main(int argc, char **argv) {
149 struct file_with_size *root;
152 for(k = 1; k < argc; k++) {
153 root = create(argv[k], root);