Fixed a bug in the arguments of raw_print and fancy_print.
[dus.git] / dus.c
1
2 /*
3  *  dus is a simple utility to display the files and directories
4  *  according to their total disk occupancy.
5  *
6  *  Copyright (c) 2010 Francois Fleuret
7  *  Written by Francois Fleuret <francois@fleuret.org>
8  *
9  *  This file is part of dus.
10  *
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.
14  *
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.
19  *
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/>.
22  *
23  */
24
25 #define _BSD_SOURCE
26
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <dirent.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <errno.h>
34 #include <string.h>
35 #include <sys/ioctl.h>
36 #include <locale.h>
37 #include <getopt.h>
38
39 #define BUFFER_SIZE 4096
40
41 typedef int64_t size_sum_t;
42
43 /* Yeah, global variables! */
44
45 int ignore_dotfiles = 0; /* 1 means ignore files and directories
46                             starting with a dot */
47
48 int forced_width = 0; /* -1 means no width limit, strictly positive
49                          means limit, 0 means not active */
50
51 int forced_height = 0; /* -1 means no height limit, strictly positive
52                            means limit, 0 means not active */
53
54 int fancy_size_display = 0; /* 1 means to use floating values with K, M and G
55                                as units */
56
57 int reverse_sorting = 0; /* 1 means to show the large ones first */
58
59 int show_top = 0; /* 1 means to show the top of the sorted list
60                      instead of the bottom */
61
62 /********************************************************************/
63
64 /* malloc with error checking.  */
65
66 void *safe_malloc(size_t n) {
67   void *p = malloc(n);
68   if (!p && n != 0) {
69     printf("Can not allocate memory: %s\n", strerror(errno));
70     exit(EXIT_FAILURE);
71   }
72   return p;
73 }
74
75 /********************************************************************/
76
77 int ignore_entry(const char *name) {
78   return
79     strcmp(name, ".") == 0 ||
80     strcmp(name, "..") == 0 ||
81     (ignore_dotfiles && name[0] == '.');
82 }
83
84 void print_size_sum(size_sum_t s) {
85   char tmp[100];
86   char *a = tmp + sizeof(tmp)/sizeof(char);
87   *(--a) = '\0';
88   if(s) {
89     while(s) {
90       *(--a) = s%10 + '0';
91       s /= 10;
92     }
93   } else {
94     *(--a) = '0';
95   }
96   printf(a);
97 }
98
99 size_sum_t file_or_dir_size(const char *name) {
100   DIR *dir;
101   struct dirent *dir_e;
102   struct stat dummy;
103   size_sum_t result;
104   char subname[BUFFER_SIZE];
105
106   result = 0;
107
108   if(lstat(name, &dummy) != 0) {
109     printf("Can not stat %s: %s\n", name, strerror(errno));
110     exit(EXIT_FAILURE);
111   }
112
113   if(S_ISLNK(dummy.st_mode)) {
114     return 0;
115   }
116
117   dir = opendir(name);
118
119   if(dir) {
120     while((dir_e = readdir(dir))) {
121       if(!ignore_entry(dir_e->d_name)) {
122         snprintf(subname, BUFFER_SIZE, "%s/%s", name, dir_e->d_name);
123         result += file_or_dir_size(subname);
124       }
125     }
126     closedir(dir);
127   } else {
128     if(S_ISREG(dummy.st_mode)) {
129       result += dummy.st_size;
130     }
131   }
132
133   return result;
134 }
135
136 /**********************************************************************/
137
138 struct file_with_size {
139   char *filename;
140   size_sum_t size;
141   struct file_with_size *next;
142 };
143
144 struct file_with_size *create(char *name, struct file_with_size *current) {
145   struct file_with_size *result;
146   result = safe_malloc(sizeof(struct file_with_size));
147   result->filename = strdup(name);
148   result->size = file_or_dir_size(name);
149   result->next = current;
150   return result;
151 }
152
153 void destroy(struct file_with_size *node) {
154   struct file_with_size *next;
155   while(node) {
156     next = node->next;
157     free(node->filename);
158     free(node);
159     node = next;
160   }
161 }
162
163 /**********************************************************************/
164
165 int compare_files(const void *x1, const void *x2) {
166   const struct file_with_size **f1, **f2;
167
168   f1 = (const struct file_with_size **) x1;
169   f2 = (const struct file_with_size **) x2;
170
171   if(reverse_sorting) {
172     if((*f1)->size < (*f2)->size) {
173       return 1;
174     } else if((*f1)->size > (*f2)->size) {
175       return -1;
176     } else {
177       return 0;
178     }
179   } else {
180     if((*f1)->size < (*f2)->size) {
181       return -1;
182     } else if((*f1)->size > (*f2)->size) {
183       return 1;
184     } else {
185       return 0;
186     }
187   }
188 }
189
190 void raw_print(char *buffer, char *filename,  size_sum_t size) {
191   char *a, *b, *c, u;
192
193   b = buffer;
194   if(size) {
195     while(size) {
196       *(b++) = size%10 + '0';
197       size /= 10;
198     }
199   } else {
200     *(b++) = '0';
201   }
202
203   a = buffer;
204   c = b;
205   while(a < c) {
206     u = *a;
207     *(a++) = *(--c);
208     *c = u;
209   }
210
211   *(b++) = ' ';
212
213   sprintf(b, " %s\n", filename);
214 }
215
216 void fancy_print(char *buffer, char *filename, size_sum_t size) {
217   if(size < 1024) {
218     sprintf(buffer,
219             "% 7d %s\n",
220             ((int) size),
221             filename);
222   } else if(size < 1024 * 1024) {
223     sprintf(buffer,
224             "% 6.1fK %s\n",
225             ((double) (size))/(1024.0),
226             filename);
227   } else if(size < 1024 * 1024 * 1024) {
228     sprintf(buffer,
229             "% 6.1fM %s\n",
230             ((double) (size))/(1024.0 * 1024),
231             filename);
232   } else {
233     sprintf(buffer,
234             "% 6.1fG %s\n",
235             ((double) (size))/(1024.0 * 1024.0 * 1024.0),
236             filename);
237   }
238 }
239
240 void print_sorted(struct file_with_size *root, int width, int height) {
241   char line[BUFFER_SIZE];
242   struct file_with_size *node;
243   struct file_with_size **nodes;
244   int nb, n, first, last;
245
246   nb = 0;
247   for(node = root; node; node = node->next) {
248     nb++;
249   }
250
251   nodes = safe_malloc(nb * sizeof(struct file_with_size *));
252
253   n = 0;
254   for(node = root; node; node = node->next) {
255     nodes[n++] = node;
256   }
257
258   qsort(nodes, nb, sizeof(struct file_with_size *), compare_files);
259
260   first = 0;
261   last = nb;
262
263   if(forced_height) {
264     height = forced_height;
265   }
266
267   if(height > 0 && height < nb) {
268     first = nb - height;
269   }
270
271   if(show_top) {
272     n = last;
273     last = nb - first;
274     first = nb - n;
275   }
276
277   for(n = first; n < last; n++) {
278     if(fancy_size_display) {
279       fancy_print(line, nodes[n]->filename, nodes[n]->size);
280     } else {
281       raw_print(line, nodes[n]->filename, nodes[n]->size);
282     }
283     if(width >= 0 && width < BUFFER_SIZE) {
284       line[width] = '\0';
285     }
286     printf(line);
287   }
288
289   free(nodes);
290 }
291
292 /**********************************************************************/
293
294 int main(int argc, char **argv) {
295   int c;
296   struct file_with_size *root;
297
298   root = 0;
299
300   setlocale (LC_ALL, "");
301
302   while (1) {
303     c = getopt(argc, argv, "dfrtl:c:hdu");
304     if (c == -1)
305       break;
306
307     switch (c) {
308
309     case 'd':
310       ignore_dotfiles = 1;
311       break;
312
313     case 'f':
314       fancy_size_display = 1;
315       break;
316
317     case 'r':
318       reverse_sorting = 1;
319       break;
320
321     case 't':
322       show_top = 1;
323       break;
324
325     case 'l':
326       forced_height = atoi(optarg);
327       break;
328
329     case 'c':
330       forced_width = atoi(optarg);
331       break;
332
333     case 'h':
334       printf("Usage: dus [OPTION]... [FILE]...\n");
335       printf("List files and directories sorted according to their size or content size. Take the content of the current directory as argument if none is provided.\n");
336       printf("\n");
337       printf("   -d          ignore files and directories starting with a '.'\n");
338       printf("   -f          display size with float values and K, M and G units.\n");
339       printf("   -r          reverse the sorting order.\n");
340       printf("   -t          show the top of the list.\n");
341       printf("   -c <cols>   specificy the number of columns to display. The value -1\n");
342       printf("               corresponds to no constraint. By default the command\n");
343       printf("               uses the tty width, or no constraint if the stdout is\n");
344       printf("               not a tty.\n");
345       printf("   -l <lines>  same as -c for number of lines.\n");
346       printf("   -h          show this help.\n");
347       printf("\n");
348       printf("Report bugs and comments to <francois@fleuret.org>\n");
349       exit(EXIT_SUCCESS);
350
351       break;
352
353     default:
354       exit(EXIT_FAILURE);
355     }
356   }
357
358   if (optind < argc) {
359     while (optind < argc) {
360       root = create(argv[optind++], root);
361     }
362   } else {
363     DIR *dir;
364     struct dirent *dir_e;
365     dir = opendir(".");
366     if(dir) {
367       while((dir_e = readdir(dir))) {
368         if(!ignore_entry(dir_e->d_name)) {
369           root = create(dir_e->d_name, root);
370         }
371       }
372       closedir(dir);
373     }
374   }
375
376   if(isatty(STDOUT_FILENO)) {
377     struct winsize win;
378     if(ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
379       printf("Can not get the tty size: %s\n", strerror(errno));
380       exit (EXIT_FAILURE);
381     }
382     print_sorted(root, win.ws_col, win.ws_row - 2);
383   } else {
384     print_sorted(root, -1, -1);
385   }
386
387   destroy(root);
388
389   exit(EXIT_SUCCESS);
390 }