cp: NEWS entry for previous fix
[coreutils.git] / src / du.c
blob4951826eae209e022cb8990379bfd7e58efb4860
1 /* du -- summarize disk usage
2 Copyright (C) 1988-1991, 1995-2010 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Differences from the Unix du:
18 * Doesn't simply ignore the names of regular files given as arguments
19 when -a is given.
21 By tege@sics.se, Torbjorn Granlund,
22 and djm@ai.mit.edu, David MacKenzie.
23 Variable blocks added by lm@sgi.com and eggert@twinsun.com.
24 Rewritten to use nftw, then to use fts by Jim Meyering. */
26 #include <config.h>
27 #include <getopt.h>
28 #include <sys/types.h>
29 #include <assert.h>
30 #include "system.h"
31 #include "argmatch.h"
32 #include "argv-iter.h"
33 #include "di-set.h"
34 #include "error.h"
35 #include "exclude.h"
36 #include "fprintftime.h"
37 #include "human.h"
38 #include "quote.h"
39 #include "quotearg.h"
40 #include "same.h"
41 #include "stat-time.h"
42 #include "stdio--.h"
43 #include "xfts.h"
44 #include "xstrtol.h"
46 extern bool fts_debug;
48 /* The official name of this program (e.g., no `g' prefix). */
49 #define PROGRAM_NAME "du"
51 #define AUTHORS \
52 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
53 proper_name ("David MacKenzie"), \
54 proper_name ("Paul Eggert"), \
55 proper_name ("Jim Meyering")
57 #if DU_DEBUG
58 # define FTS_CROSS_CHECK(Fts) fts_cross_check (Fts)
59 #else
60 # define FTS_CROSS_CHECK(Fts)
61 #endif
63 /* A set of dev/ino pairs. */
64 static struct di_set *di_set;
66 /* Define a class for collecting directory information. */
68 struct duinfo
70 /* Size of files in directory. */
71 uintmax_t size;
73 /* Latest time stamp found. If tmax.tv_sec == TYPE_MINIMUM (time_t)
74 && tmax.tv_nsec < 0, no time stamp has been found. */
75 struct timespec tmax;
78 /* Initialize directory data. */
79 static inline void
80 duinfo_init (struct duinfo *a)
82 a->size = 0;
83 a->tmax.tv_sec = TYPE_MINIMUM (time_t);
84 a->tmax.tv_nsec = -1;
87 /* Set directory data. */
88 static inline void
89 duinfo_set (struct duinfo *a, uintmax_t size, struct timespec tmax)
91 a->size = size;
92 a->tmax = tmax;
95 /* Accumulate directory data. */
96 static inline void
97 duinfo_add (struct duinfo *a, struct duinfo const *b)
99 a->size += b->size;
100 if (timespec_cmp (a->tmax, b->tmax) < 0)
101 a->tmax = b->tmax;
104 /* A structure for per-directory level information. */
105 struct dulevel
107 /* Entries in this directory. */
108 struct duinfo ent;
110 /* Total for subdirectories. */
111 struct duinfo subdir;
114 /* If true, display counts for all files, not just directories. */
115 static bool opt_all = false;
117 /* If true, rather than using the disk usage of each file,
118 use the apparent size (a la stat.st_size). */
119 static bool apparent_size = false;
121 /* If true, count each hard link of files with multiple links. */
122 static bool opt_count_all = false;
124 /* If true, hash all files to look for hard links. */
125 static bool hash_all;
127 /* If true, output the NUL byte instead of a newline at the end of each line. */
128 static bool opt_nul_terminate_output = false;
130 /* If true, print a grand total at the end. */
131 static bool print_grand_total = false;
133 /* If nonzero, do not add sizes of subdirectories. */
134 static bool opt_separate_dirs = false;
136 /* Show the total for each directory (and file if --all) that is at
137 most MAX_DEPTH levels down from the root of the hierarchy. The root
138 is at level 0, so `du --max-depth=0' is equivalent to `du -s'. */
139 static size_t max_depth = SIZE_MAX;
141 /* Human-readable options for output. */
142 static int human_output_opts;
144 /* If true, print most recently modified date, using the specified format. */
145 static bool opt_time = false;
147 /* Type of time to display. controlled by --time. */
149 enum time_type
151 time_mtime, /* default */
152 time_ctime,
153 time_atime
156 static enum time_type time_type = time_mtime;
158 /* User specified date / time style */
159 static char const *time_style = NULL;
161 /* Format used to display date / time. Controlled by --time-style */
162 static char const *time_format = NULL;
164 /* The units to use when printing sizes. */
165 static uintmax_t output_block_size;
167 /* File name patterns to exclude. */
168 static struct exclude *exclude;
170 /* Grand total size of all args, in bytes. Also latest modified date. */
171 static struct duinfo tot_dui;
173 #define IS_DIR_TYPE(Type) \
174 ((Type) == FTS_DP \
175 || (Type) == FTS_DNR)
177 /* For long options that have no equivalent short option, use a
178 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
179 enum
181 APPARENT_SIZE_OPTION = CHAR_MAX + 1,
182 EXCLUDE_OPTION,
183 FILES0_FROM_OPTION,
184 HUMAN_SI_OPTION,
185 FTS_DEBUG,
186 TIME_OPTION,
187 TIME_STYLE_OPTION
190 static struct option const long_options[] =
192 {"all", no_argument, NULL, 'a'},
193 {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
194 {"block-size", required_argument, NULL, 'B'},
195 {"bytes", no_argument, NULL, 'b'},
196 {"count-links", no_argument, NULL, 'l'},
197 /* {"-debug", no_argument, NULL, FTS_DEBUG}, */
198 {"dereference", no_argument, NULL, 'L'},
199 {"dereference-args", no_argument, NULL, 'D'},
200 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
201 {"exclude-from", required_argument, NULL, 'X'},
202 {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
203 {"human-readable", no_argument, NULL, 'h'},
204 {"si", no_argument, NULL, HUMAN_SI_OPTION},
205 {"max-depth", required_argument, NULL, 'd'},
206 {"null", no_argument, NULL, '0'},
207 {"no-dereference", no_argument, NULL, 'P'},
208 {"one-file-system", no_argument, NULL, 'x'},
209 {"separate-dirs", no_argument, NULL, 'S'},
210 {"summarize", no_argument, NULL, 's'},
211 {"total", no_argument, NULL, 'c'},
212 {"time", optional_argument, NULL, TIME_OPTION},
213 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
214 {GETOPT_HELP_OPTION_DECL},
215 {GETOPT_VERSION_OPTION_DECL},
216 {NULL, 0, NULL, 0}
219 static char const *const time_args[] =
221 "atime", "access", "use", "ctime", "status", NULL
223 static enum time_type const time_types[] =
225 time_atime, time_atime, time_atime, time_ctime, time_ctime
227 ARGMATCH_VERIFY (time_args, time_types);
229 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
230 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
231 ISO-style time stamps. */
232 enum time_style
234 full_iso_time_style, /* --time-style=full-iso */
235 long_iso_time_style, /* --time-style=long-iso */
236 iso_time_style /* --time-style=iso */
239 static char const *const time_style_args[] =
241 "full-iso", "long-iso", "iso", NULL
243 static enum time_style const time_style_types[] =
245 full_iso_time_style, long_iso_time_style, iso_time_style
247 ARGMATCH_VERIFY (time_style_args, time_style_types);
249 void
250 usage (int status)
252 if (status != EXIT_SUCCESS)
253 fprintf (stderr, _("Try `%s --help' for more information.\n"),
254 program_name);
255 else
257 printf (_("\
258 Usage: %s [OPTION]... [FILE]...\n\
259 or: %s [OPTION]... --files0-from=F\n\
260 "), program_name, program_name);
261 fputs (_("\
262 Summarize disk usage of each FILE, recursively for directories.\n\
264 "), stdout);
265 fputs (_("\
266 Mandatory arguments to long options are mandatory for short options too.\n\
267 "), stdout);
268 fputs (_("\
269 -a, --all write counts for all files, not just directories\n\
270 --apparent-size print apparent sizes, rather than disk usage; although\n\
271 the apparent size is usually smaller, it may be\n\
272 larger due to holes in (`sparse') files, internal\n\
273 fragmentation, indirect blocks, and the like\n\
274 "), stdout);
275 fputs (_("\
276 -B, --block-size=SIZE scale sizes by SIZE before printing them. E.g.,\n\
277 `-BM' prints sizes in units of 1,048,576 bytes.\n\
278 See SIZE format below.\n\
279 -b, --bytes equivalent to `--apparent-size --block-size=1'\n\
280 -c, --total produce a grand total\n\
281 -D, --dereference-args dereference only symlinks that are listed on the\n\
282 command line\n\
283 "), stdout);
284 fputs (_("\
285 --files0-from=F summarize disk usage of the NUL-terminated file\n\
286 names specified in file F;\n\
287 If F is - then read names from standard input\n\
288 -H equivalent to --dereference-args (-D)\n\
289 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
290 --si like -h, but use powers of 1000 not 1024\n\
291 "), stdout);
292 fputs (_("\
293 -k like --block-size=1K\n\
294 -l, --count-links count sizes many times if hard linked\n\
295 -m like --block-size=1M\n\
296 "), stdout);
297 fputs (_("\
298 -L, --dereference dereference all symbolic links\n\
299 -P, --no-dereference don't follow any symbolic links (this is the default)\n\
300 -0, --null end each output line with 0 byte rather than newline\n\
301 -S, --separate-dirs do not include size of subdirectories\n\
302 -s, --summarize display only a total for each argument\n\
303 "), stdout);
304 fputs (_("\
305 -x, --one-file-system skip directories on different file systems\n\
306 -X, --exclude-from=FILE exclude files that match any pattern in FILE\n\
307 --exclude=PATTERN exclude files that match PATTERN\n\
308 -d, --max-depth=N print the total for a directory (or file, with --all)\n\
309 only if it is N or fewer levels below the command\n\
310 line argument; --max-depth=0 is the same as\n\
311 --summarize\n\
312 "), stdout);
313 fputs (_("\
314 --time show time of the last modification of any file in the\n\
315 directory, or any of its subdirectories\n\
316 --time=WORD show time as WORD instead of modification time:\n\
317 atime, access, use, ctime or status\n\
318 --time-style=STYLE show times using style STYLE:\n\
319 full-iso, long-iso, iso, +FORMAT\n\
320 FORMAT is interpreted like `date'\n\
321 "), stdout);
322 fputs (HELP_OPTION_DESCRIPTION, stdout);
323 fputs (VERSION_OPTION_DESCRIPTION, stdout);
324 emit_blocksize_note ("DU");
325 emit_size_note ();
326 emit_ancillary_info ();
328 exit (status);
331 /* Try to insert the INO/DEV pair into the global table, HTAB.
332 Return true if the pair is successfully inserted,
333 false if the pair is already in the table. */
334 static bool
335 hash_ins (ino_t ino, dev_t dev)
337 int inserted = di_set_insert (di_set, dev, ino);
338 if (inserted < 0)
339 xalloc_die ();
340 return inserted;
343 /* FIXME: this code is nearly identical to code in date.c */
344 /* Display the date and time in WHEN according to the format specified
345 in FORMAT. */
347 static void
348 show_date (const char *format, struct timespec when)
350 struct tm *tm = localtime (&when.tv_sec);
351 if (! tm)
353 char buf[INT_BUFSIZE_BOUND (intmax_t)];
354 char *when_str = timetostr (when.tv_sec, buf);
355 error (0, 0, _("time %s is out of range"), when_str);
356 fputs (when_str, stdout);
357 return;
360 fprintftime (stdout, format, tm, 0, when.tv_nsec);
363 /* Print N_BYTES. Convert it to a readable value before printing. */
365 static void
366 print_only_size (uintmax_t n_bytes)
368 char buf[LONGEST_HUMAN_READABLE + 1];
369 fputs (human_readable (n_bytes, buf, human_output_opts,
370 1, output_block_size), stdout);
373 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
375 static void
376 print_size (const struct duinfo *pdui, const char *string)
378 print_only_size (pdui->size);
379 if (opt_time)
381 putchar ('\t');
382 show_date (time_format, pdui->tmax);
384 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
385 fflush (stdout);
388 /* This function is called once for every file system object that fts
389 encounters. fts does a depth-first traversal. This function knows
390 that and accumulates per-directory totals based on changes in
391 the depth of the current entry. It returns true on success. */
393 static bool
394 process_file (FTS *fts, FTSENT *ent)
396 bool ok = true;
397 struct duinfo dui;
398 struct duinfo dui_to_print;
399 size_t level;
400 static size_t prev_level;
401 static size_t n_alloc;
402 /* First element of the structure contains:
403 The sum of the st_size values of all entries in the single directory
404 at the corresponding level. Although this does include the st_size
405 corresponding to each subdirectory, it does not include the size of
406 any file in a subdirectory. Also corresponding last modified date.
407 Second element of the structure contains:
408 The sum of the sizes of all entries in the hierarchy at or below the
409 directory at the specified level. */
410 static struct dulevel *dulvl;
412 const char *file = ent->fts_path;
413 const struct stat *sb = ent->fts_statp;
414 int info = ent->fts_info;
416 if (info == FTS_DNR)
418 /* An error occurred, but the size is known, so count it. */
419 error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
420 ok = false;
422 else if (info != FTS_DP)
424 bool excluded = excluded_file_name (exclude, file);
425 if (! excluded)
427 /* Make the stat buffer *SB valid, or fail noisily. */
429 if (info == FTS_NSOK)
431 fts_set (fts, ent, FTS_AGAIN);
432 FTSENT const *e = fts_read (fts);
433 assert (e == ent);
434 info = ent->fts_info;
437 if (info == FTS_NS || info == FTS_SLNONE)
439 error (0, ent->fts_errno, _("cannot access %s"), quote (file));
440 return false;
444 if (excluded
445 || (! opt_count_all
446 && (hash_all || (! S_ISDIR (sb->st_mode) && 1 < sb->st_nlink))
447 && ! hash_ins (sb->st_ino, sb->st_dev)))
449 /* If ignoring a directory in preorder, skip its children.
450 Ignore the next fts_read output too, as it's a postorder
451 visit to the same directory. */
452 if (info == FTS_D)
454 fts_set (fts, ent, FTS_SKIP);
455 FTSENT const *e = fts_read (fts);
456 assert (e == ent);
459 return true;
462 switch (info)
464 case FTS_D:
465 return true;
467 case FTS_ERR:
468 /* An error occurred, but the size is known, so count it. */
469 error (0, ent->fts_errno, "%s", quote (file));
470 ok = false;
471 break;
473 case FTS_DC:
474 if (cycle_warning_required (fts, ent))
476 emit_cycle_warning (file);
477 return false;
479 return true;
483 duinfo_set (&dui,
484 (apparent_size
485 ? sb->st_size
486 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
487 (time_type == time_mtime ? get_stat_mtime (sb)
488 : time_type == time_atime ? get_stat_atime (sb)
489 : get_stat_ctime (sb)));
491 level = ent->fts_level;
492 dui_to_print = dui;
494 if (n_alloc == 0)
496 n_alloc = level + 10;
497 dulvl = xcalloc (n_alloc, sizeof *dulvl);
499 else
501 if (level == prev_level)
503 /* This is usually the most common case. Do nothing. */
505 else if (level > prev_level)
507 /* Descending the hierarchy.
508 Clear the accumulators for *all* levels between prev_level
509 and the current one. The depth may change dramatically,
510 e.g., from 1 to 10. */
511 size_t i;
513 if (n_alloc <= level)
515 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
516 n_alloc = level * 2;
519 for (i = prev_level + 1; i <= level; i++)
521 duinfo_init (&dulvl[i].ent);
522 duinfo_init (&dulvl[i].subdir);
525 else /* level < prev_level */
527 /* Ascending the hierarchy.
528 Process a directory only after all entries in that
529 directory have been processed. When the depth decreases,
530 propagate sums from the children (prev_level) to the parent.
531 Here, the current level is always one smaller than the
532 previous one. */
533 assert (level == prev_level - 1);
534 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
535 if (!opt_separate_dirs)
536 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
537 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
538 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
542 prev_level = level;
544 /* Let the size of a directory entry contribute to the total for the
545 containing directory, unless --separate-dirs (-S) is specified. */
546 if (! (opt_separate_dirs && IS_DIR_TYPE (info)))
547 duinfo_add (&dulvl[level].ent, &dui);
549 /* Even if this directory is unreadable or we can't chdir into it,
550 do let its size contribute to the total. */
551 duinfo_add (&tot_dui, &dui);
553 if ((IS_DIR_TYPE (info) && level <= max_depth)
554 || ((opt_all && level <= max_depth) || level == 0))
555 print_size (&dui_to_print, file);
557 return ok;
560 /* Recursively print the sizes of the directories (and, if selected, files)
561 named in FILES, the last entry of which is NULL.
562 BIT_FLAGS controls how fts works.
563 Return true if successful. */
565 static bool
566 du_files (char **files, int bit_flags)
568 bool ok = true;
570 if (*files)
572 FTS *fts = xfts_open (files, bit_flags, NULL);
574 while (1)
576 FTSENT *ent;
578 ent = fts_read (fts);
579 if (ent == NULL)
581 if (errno != 0)
583 /* FIXME: try to give a better message */
584 error (0, errno, _("fts_read failed"));
585 ok = false;
587 break;
589 FTS_CROSS_CHECK (fts);
591 ok &= process_file (fts, ent);
594 if (fts_close (fts) != 0)
596 error (0, errno, _("fts_close failed"));
597 ok = false;
601 return ok;
605 main (int argc, char **argv)
607 char *cwd_only[2];
608 bool max_depth_specified = false;
609 bool ok = true;
610 char *files_from = NULL;
612 /* Bit flags that control how fts works. */
613 int bit_flags = FTS_NOSTAT;
615 /* Select one of the three FTS_ options that control if/when
616 to follow a symlink. */
617 int symlink_deref_bits = FTS_PHYSICAL;
619 /* If true, display only a total for each argument. */
620 bool opt_summarize_only = false;
622 cwd_only[0] = bad_cast (".");
623 cwd_only[1] = NULL;
625 initialize_main (&argc, &argv);
626 set_program_name (argv[0]);
627 setlocale (LC_ALL, "");
628 bindtextdomain (PACKAGE, LOCALEDIR);
629 textdomain (PACKAGE);
631 atexit (close_stdout);
633 exclude = new_exclude ();
635 human_options (getenv ("DU_BLOCK_SIZE"),
636 &human_output_opts, &output_block_size);
638 while (true)
640 int oi = -1;
641 int c = getopt_long (argc, argv, "0abd:chHklmsxB:DLPSX:",
642 long_options, &oi);
643 if (c == -1)
644 break;
646 switch (c)
648 #if DU_DEBUG
649 case FTS_DEBUG:
650 fts_debug = true;
651 break;
652 #endif
654 case '0':
655 opt_nul_terminate_output = true;
656 break;
658 case 'a':
659 opt_all = true;
660 break;
662 case APPARENT_SIZE_OPTION:
663 apparent_size = true;
664 break;
666 case 'b':
667 apparent_size = true;
668 human_output_opts = 0;
669 output_block_size = 1;
670 break;
672 case 'c':
673 print_grand_total = true;
674 break;
676 case 'h':
677 human_output_opts = human_autoscale | human_SI | human_base_1024;
678 output_block_size = 1;
679 break;
681 case HUMAN_SI_OPTION:
682 human_output_opts = human_autoscale | human_SI;
683 output_block_size = 1;
684 break;
686 case 'k':
687 human_output_opts = 0;
688 output_block_size = 1024;
689 break;
691 case 'd': /* --max-depth=N */
693 unsigned long int tmp_ulong;
694 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
695 && tmp_ulong <= SIZE_MAX)
697 max_depth_specified = true;
698 max_depth = tmp_ulong;
700 else
702 error (0, 0, _("invalid maximum depth %s"),
703 quote (optarg));
704 ok = false;
707 break;
709 case 'm':
710 human_output_opts = 0;
711 output_block_size = 1024 * 1024;
712 break;
714 case 'l':
715 opt_count_all = true;
716 break;
718 case 's':
719 opt_summarize_only = true;
720 break;
722 case 'x':
723 bit_flags |= FTS_XDEV;
724 break;
726 case 'B':
728 enum strtol_error e = human_options (optarg, &human_output_opts,
729 &output_block_size);
730 if (e != LONGINT_OK)
731 xstrtol_fatal (e, oi, c, long_options, optarg);
733 break;
735 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
736 case 'D':
737 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
738 break;
740 case 'L': /* --dereference */
741 symlink_deref_bits = FTS_LOGICAL;
742 break;
744 case 'P': /* --no-dereference */
745 symlink_deref_bits = FTS_PHYSICAL;
746 break;
748 case 'S':
749 opt_separate_dirs = true;
750 break;
752 case 'X':
753 if (add_exclude_file (add_exclude, exclude, optarg,
754 EXCLUDE_WILDCARDS, '\n'))
756 error (0, errno, "%s", quotearg_colon (optarg));
757 ok = false;
759 break;
761 case FILES0_FROM_OPTION:
762 files_from = optarg;
763 break;
765 case EXCLUDE_OPTION:
766 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
767 break;
769 case TIME_OPTION:
770 opt_time = true;
771 time_type =
772 (optarg
773 ? XARGMATCH ("--time", optarg, time_args, time_types)
774 : time_mtime);
775 break;
777 case TIME_STYLE_OPTION:
778 time_style = optarg;
779 break;
781 case_GETOPT_HELP_CHAR;
783 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
785 default:
786 ok = false;
790 if (!ok)
791 usage (EXIT_FAILURE);
793 if (opt_all && opt_summarize_only)
795 error (0, 0, _("cannot both summarize and show all entries"));
796 usage (EXIT_FAILURE);
799 if (opt_summarize_only && max_depth_specified && max_depth == 0)
801 error (0, 0,
802 _("warning: summarizing is the same as using --max-depth=0"));
805 if (opt_summarize_only && max_depth_specified && max_depth != 0)
807 unsigned long int d = max_depth;
808 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
809 usage (EXIT_FAILURE);
812 if (opt_summarize_only)
813 max_depth = 0;
815 /* Process time style if printing last times. */
816 if (opt_time)
818 if (! time_style)
820 time_style = getenv ("TIME_STYLE");
822 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
823 if (! time_style || STREQ (time_style, "locale"))
824 time_style = "long-iso";
825 else if (*time_style == '+')
827 /* Ignore anything after a newline, for compatibility
828 with ls. */
829 char *p = strchr (time_style, '\n');
830 if (p)
831 *p = '\0';
833 else
835 /* Ignore "posix-" prefix, for compatibility with ls. */
836 static char const posix_prefix[] = "posix-";
837 while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1)
838 == 0)
839 time_style += sizeof posix_prefix - 1;
843 if (*time_style == '+')
844 time_format = time_style + 1;
845 else
847 switch (XARGMATCH ("time style", time_style,
848 time_style_args, time_style_types))
850 case full_iso_time_style:
851 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
852 break;
854 case long_iso_time_style:
855 time_format = "%Y-%m-%d %H:%M";
856 break;
858 case iso_time_style:
859 time_format = "%Y-%m-%d";
860 break;
865 struct argv_iterator *ai;
866 if (files_from)
868 /* When using --files0-from=F, you may not specify any files
869 on the command-line. */
870 if (optind < argc)
872 error (0, 0, _("extra operand %s"), quote (argv[optind]));
873 fprintf (stderr, "%s\n",
874 _("file operands cannot be combined with --files0-from"));
875 usage (EXIT_FAILURE);
878 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
879 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
880 quote (files_from));
882 ai = argv_iter_init_stream (stdin);
884 /* It's not easy here to count the arguments, so assume the
885 worst. */
886 hash_all = true;
888 else
890 char **files = (optind < argc ? argv + optind : cwd_only);
891 ai = argv_iter_init_argv (files);
893 /* Hash all dev,ino pairs if there are multiple arguments, or if
894 following non-command-line symlinks, because in either case a
895 file with just one hard link might be seen more than once. */
896 hash_all = (optind + 1 < argc || symlink_deref_bits == FTS_LOGICAL);
899 if (!ai)
900 xalloc_die ();
902 /* Initialize the set of dev,inode pairs. */
903 di_set = di_set_alloc ();
904 if (!di_set)
905 xalloc_die ();
907 /* If not hashing everything, process_file won't find cycles on its
908 own, so ask fts_read to check for them accurately. */
909 if (opt_count_all || ! hash_all)
910 bit_flags |= FTS_TIGHT_CYCLE_CHECK;
912 bit_flags |= symlink_deref_bits;
913 static char *temp_argv[] = { NULL, NULL };
915 while (true)
917 bool skip_file = false;
918 enum argv_iter_err ai_err;
919 char *file_name = argv_iter (ai, &ai_err);
920 if (ai_err == AI_ERR_EOF)
921 break;
922 if (!file_name)
924 switch (ai_err)
926 case AI_ERR_READ:
927 error (0, errno, _("%s: read error"), quote (files_from));
928 continue;
930 case AI_ERR_MEM:
931 xalloc_die ();
933 default:
934 assert (!"unexpected error code from argv_iter");
937 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
939 /* Give a better diagnostic in an unusual case:
940 printf - | du --files0-from=- */
941 error (0, 0, _("when reading file names from stdin, "
942 "no file name of %s allowed"),
943 quote (file_name));
944 skip_file = true;
947 /* Report and skip any empty file names before invoking fts.
948 This works around a glitch in fts, which fails immediately
949 (without looking at the other file names) when given an empty
950 file name. */
951 if (!file_name[0])
953 /* Diagnose a zero-length file name. When it's one
954 among many, knowing the record number may help.
955 FIXME: currently print the record number only with
956 --files0-from=FILE. Maybe do it for argv, too? */
957 if (files_from == NULL)
958 error (0, 0, "%s", _("invalid zero-length file name"));
959 else
961 /* Using the standard `filename:line-number:' prefix here is
962 not totally appropriate, since NUL is the separator, not NL,
963 but it might be better than nothing. */
964 unsigned long int file_number = argv_iter_n_args (ai);
965 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
966 file_number, _("invalid zero-length file name"));
968 skip_file = true;
971 if (skip_file)
972 ok = false;
973 else
975 temp_argv[0] = file_name;
976 ok &= du_files (temp_argv, bit_flags);
980 argv_iter_free (ai);
981 di_set_free (di_set);
983 if (files_from && (ferror (stdin) || fclose (stdin) != 0))
984 error (EXIT_FAILURE, 0, _("error reading %s"), quote (files_from));
986 if (print_grand_total)
987 print_size (&tot_dui, _("total"));
989 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);