home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 2 / FFMCD02.bin / useful / dist / gnu / fileutils / fileutils-3.9-amiga / src / ls.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-13  |  43.3 KB  |  1,945 lines

  1. /* `dir', `vdir' and `ls' directory listing programs for GNU.
  2.    Copyright (C) 1985, 1988, 1990, 1991 Free Software Foundation, Inc.
  3.  
  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 2, or (at your option)
  7.    any later version.
  8.  
  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.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* If the macro MULTI_COL is defined,
  19.    the multi-column format is the default regardless
  20.    of the type of output device.
  21.    This is for the `dir' program.
  22.  
  23.    If the macro LONG_FORMAT is defined,
  24.    the long format is the default regardless of the
  25.    type of output device.
  26.    This is for the `vdir' program.
  27.  
  28.    If neither is defined,
  29.    the output format depends on whether the output
  30.    device is a terminal.
  31.    This is for the `ls' program. */
  32.  
  33. /* Written by Richard Stallman and David MacKenzie. */
  34.  
  35. #ifdef _AIX
  36.  #pragma alloca
  37. #endif
  38.  
  39. #ifdef HAVE_CONFIG_H
  40. #if defined (CONFIG_BROKETS)
  41. /* We use <config.h> instead of "config.h" so that a compilation
  42.    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
  43.    (which it would do because it found this file in $srcdir).  */
  44. #include <config.h>
  45. #else
  46. #include "config.h"
  47. #endif
  48. #endif
  49.  
  50. #include <sys/types.h>
  51. #if !defined(_POSIX_SOURCE) || defined(_AIX)
  52. #include <sys/ioctl.h>
  53. #endif
  54. #include <stdio.h>
  55. #include <grp.h>
  56. #include <pwd.h>
  57. #include <getopt.h>
  58. #include "system.h"
  59. #include <fnmatch.h>
  60.  
  61. #include "ls.h"
  62. #include "version.h"
  63.  
  64. #ifndef S_IEXEC
  65. #define S_IEXEC S_IXUSR
  66. #endif
  67.  
  68. /* Return an int indicating the result of comparing two longs. */
  69. #ifdef INT_16_BITS
  70. #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
  71. #else
  72. #define longdiff(a, b) ((a) - (b))
  73. #endif
  74.  
  75. #ifndef STDC_HEADERS
  76. char *ctime ();
  77. time_t time ();
  78. #endif
  79.  
  80. void mode_string ();
  81.  
  82. char *xstrdup ();
  83. char *getgroup ();
  84. char *getuser ();
  85. char *xmalloc ();
  86. char *xrealloc ();
  87. int argmatch ();
  88. void error ();
  89. void invalid_arg ();
  90.  
  91. static char *make_link_path ();
  92. static int compare_atime ();
  93. static int rev_cmp_atime ();
  94. static int compare_ctime ();
  95. static int rev_cmp_ctime ();
  96. static int compare_mtime ();
  97. static int rev_cmp_mtime ();
  98. static int compare_size ();
  99. static int rev_cmp_size ();
  100. static int compare_name ();
  101. static int rev_cmp_name ();
  102. static int compare_extension ();
  103. static int rev_cmp_extension ();
  104. static int decode_switches ();
  105. static int file_interesting ();
  106. static int gobble_file ();
  107. static int is_not_dot_or_dotdot ();
  108. static int length_of_file_name_and_frills ();
  109. static void add_ignore_pattern ();
  110. static void attach ();
  111. static void clear_files ();
  112. static void extract_dirs_from_files ();
  113. static void get_link_name ();
  114. static void indent ();
  115. static void print_current_files ();
  116. static void print_dir ();
  117. static void print_file_name_and_frills ();
  118. static void print_horizontal ();
  119. static void print_long_format ();
  120. static void print_many_per_line ();
  121. static void print_name_with_quoting ();
  122. static void print_type_indicator ();
  123. static void print_with_commas ();
  124. static void queue_directory ();
  125. static void sort_files ();
  126. static void usage ();
  127.  
  128.  
  129. /* The name the program was run with, stripped of any leading path. */
  130. char *program_name;
  131.  
  132. enum filetype
  133. {
  134.   symbolic_link,
  135.   directory,
  136.   arg_directory,        /* Directory given as command line arg. */
  137.   normal            /* All others. */
  138. };
  139.  
  140. struct file
  141. {
  142.   /* The file name. */
  143.   char *name;
  144.  
  145.   struct stat stat;
  146.  
  147.   /* For symbolic link, name of the file linked to, otherwise zero. */
  148.   char *linkname;
  149.  
  150.   /* For symbolic link and long listing, st_mode of file linked to, otherwise
  151.      zero. */
  152.   unsigned int linkmode;
  153.  
  154.   enum filetype filetype;
  155. };
  156.  
  157. /* The table of files in the current directory:
  158.  
  159.    `files' points to a vector of `struct file', one per file.
  160.    `nfiles' is the number of elements space has been allocated for.
  161.    `files_index' is the number actually in use.  */
  162.  
  163. /* Address of block containing the files that are described.  */
  164.  
  165. static struct file *files;
  166.  
  167. /* Length of block that `files' points to, measured in files.  */
  168.  
  169. static int nfiles;
  170.  
  171. /* Index of first unused in `files'.  */
  172.  
  173. static int files_index;
  174.  
  175. /* Record of one pending directory waiting to be listed.  */
  176.  
  177. struct pending
  178. {
  179.   char *name;
  180.   /* If the directory is actually the file pointed to by a symbolic link we
  181.      were told to list, `realname' will contain the name of the symbolic
  182.      link, otherwise zero. */
  183.   char *realname;
  184.   struct pending *next;
  185. };
  186.  
  187. static struct pending *pending_dirs;
  188.  
  189. /* Current time (seconds since 1970).  When we are printing a file's time,
  190.    include the year if it is more than 6 months before this time.  */
  191.  
  192. static time_t current_time;
  193.  
  194. /* The number of digits to use for block sizes.
  195.    4, or more if needed for bigger numbers.  */
  196.  
  197. static int block_size_size;
  198.  
  199. /* Option flags */
  200.  
  201. /* long_format for lots of info, one per line.
  202.    one_per_line for just names, one per line.
  203.    many_per_line for just names, many per line, sorted vertically.
  204.    horizontal for just names, many per line, sorted horizontally.
  205.    with_commas for just names, many per line, separated by commas.
  206.  
  207.    -l, -1, -C, -x and -m control this parameter.  */
  208.  
  209. enum format
  210. {
  211.   long_format,            /* -l */
  212.   one_per_line,            /* -1 */
  213.   many_per_line,        /* -C */
  214.   horizontal,            /* -x */
  215.   with_commas            /* -m */
  216. };
  217.  
  218. static enum format format;
  219.  
  220. /* Type of time to print or sort by.  Controlled by -c and -u.  */
  221.  
  222. enum time_type
  223. {
  224.   time_mtime,            /* default */
  225.   time_ctime,            /* -c */
  226.   time_atime            /* -u */
  227. };
  228.  
  229. static enum time_type time_type;
  230.  
  231. /* print the full time, otherwise the standard unix heuristics. */
  232.  
  233. int full_time;
  234.  
  235. /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X. */
  236.  
  237. enum sort_type
  238. {
  239.   sort_none,            /* -U */
  240.   sort_name,            /* default */
  241.   sort_extension,        /* -X */
  242.   sort_time,            /* -t */
  243.   sort_size            /* -S */
  244. };
  245.  
  246. static enum sort_type sort_type;
  247.  
  248. /* Direction of sort.
  249.    0 means highest first if numeric,
  250.    lowest first if alphabetic;
  251.    these are the defaults.
  252.    1 means the opposite order in each case.  -r  */
  253.  
  254. static int sort_reverse;
  255.  
  256. /* Nonzero means to NOT display group information.  -G  */
  257.  
  258. int inhibit_group;
  259.  
  260. /* Nonzero means print the user and group id's as numbers rather
  261.    than as names.  -n  */
  262.  
  263. static int numeric_users;
  264.  
  265. /* Nonzero means mention the size in 512 byte blocks of each file.  -s  */
  266.  
  267. static int print_block_size;
  268.  
  269. /* Nonzero means show file sizes in kilobytes instead of blocks
  270.    (the size of which is system-dependent).  -k */
  271.  
  272. static int kilobyte_blocks;
  273.  
  274. /* none means don't mention the type of files.
  275.    all means mention the types of all files.
  276.    not_programs means do so except for executables.
  277.  
  278.    Controlled by -F and -p.  */
  279.  
  280. enum indicator_style
  281. {
  282.   none,                /* default */
  283.   all,                /* -F */
  284.   not_programs            /* -p */
  285. };
  286.  
  287. static enum indicator_style indicator_style;
  288.  
  289. /* Nonzero means mention the inode number of each file.  -i  */
  290.  
  291. static int print_inode;
  292.  
  293. /* Nonzero means when a symbolic link is found, display info on
  294.    the file linked to.  -L  */
  295.  
  296. static int trace_links;
  297.  
  298. /* Nonzero means when a directory is found, display info on its
  299.    contents.  -R  */
  300.  
  301. static int trace_dirs;
  302.  
  303. /* Nonzero means when an argument is a directory name, display info
  304.    on it itself.  -d  */
  305.  
  306. static int immediate_dirs;
  307.  
  308. /* Nonzero means don't omit files whose names start with `.'.  -A */
  309.  
  310. static int all_files;
  311.  
  312. /* Nonzero means don't omit files `.' and `..'
  313.    This flag implies `all_files'.  -a  */
  314.  
  315. static int really_all_files;
  316.  
  317. /* A linked list of shell-style globbing patterns.  If a non-argument
  318.    file name matches any of these patterns, it is omitted.
  319.    Controlled by -I.  Multiple -I options accumulate.
  320.    The -B option adds `*~' and `.*~' to this list.  */
  321.  
  322. struct ignore_pattern
  323. {
  324.   char *pattern;
  325.   struct ignore_pattern *next;
  326. };
  327.  
  328. static struct ignore_pattern *ignore_patterns;
  329.  
  330. /* Nonzero means quote nongraphic chars in file names.  -b  */
  331.  
  332. static int quote_funny_chars;
  333.  
  334. /* Nonzero means output nongraphic chars in file names as `?'.  -q  */
  335.  
  336. static int qmark_funny_chars;
  337.  
  338. /* Nonzero means output each file name using C syntax for a string.
  339.    Always accompanied by `quote_funny_chars'.
  340.    This mode, together with -x or -C or -m,
  341.    and without such frills as -F or -s,
  342.    is guaranteed to make it possible for a program receiving
  343.    the output to tell exactly what file names are present.  -Q  */
  344.  
  345. static int quote_as_string;
  346.  
  347. /* The number of chars per hardware tab stop.  -T */
  348. static int tabsize;
  349.  
  350. /* Nonzero means we are listing the working directory because no
  351.    non-option arguments were given. */
  352.  
  353. static int dir_defaulted;
  354.  
  355. /* Nonzero means print each directory name before listing it. */
  356.  
  357. static int print_dir_name;
  358.  
  359. /* The line length to use for breaking lines in many-per-line format.
  360.    Can be set with -w.  */
  361.  
  362. static int line_length;
  363.  
  364. /* If nonzero, the file listing format requires that stat be called on
  365.    each file. */
  366.  
  367. static int format_needs_stat;
  368.  
  369. /* The exit status to use if we don't get any fatal errors. */
  370.  
  371. static int exit_status;
  372.  
  373. /* If non-zero, display usage information and exit.  */
  374. static int show_help;
  375.  
  376. /* If non-zero, print the version on standard output and exit.  */
  377. static int show_version;
  378.  
  379. static struct option const long_options[] =
  380. {
  381.   {"all", no_argument, 0, 'a'},
  382.   {"escape", no_argument, 0, 'b'},
  383.   {"directory", no_argument, 0, 'd'},
  384.   {"full-time", no_argument, &full_time, 1},
  385.   {"inode", no_argument, 0, 'i'},
  386.   {"kilobytes", no_argument, 0, 'k'},
  387.   {"numeric-uid-gid", no_argument, 0, 'n'},
  388.   {"no-group", no_argument, 0, 'G'},
  389.   {"hide-control-chars", no_argument, 0, 'q'},
  390.   {"reverse", no_argument, 0, 'r'},
  391.   {"size", no_argument, 0, 's'},
  392.   {"width", required_argument, 0, 'w'},
  393.   {"almost-all", no_argument, 0, 'A'},
  394.   {"ignore-backups", no_argument, 0, 'B'},
  395.   {"classify", no_argument, 0, 'F'},
  396.   {"file-type", no_argument, 0, 'F'},
  397.   {"ignore", required_argument, 0, 'I'},
  398.   {"dereference", no_argument, 0, 'L'},
  399.   {"literal", no_argument, 0, 'N'},
  400.   {"quote-name", no_argument, 0, 'Q'},
  401.   {"recursive", no_argument, 0, 'R'},
  402.   {"format", required_argument, 0, 12},
  403.   {"sort", required_argument, 0, 10},
  404.   {"tabsize", required_argument, 0, 'T'},
  405.   {"time", required_argument, 0, 11},
  406.   {"help", no_argument, &show_help, 1},
  407.   {"version", no_argument, &show_version, 1},
  408.   {0, 0, 0, 0}
  409. };
  410.  
  411. static char const* const format_args[] =
  412. {
  413.   "verbose", "long", "commas", "horizontal", "across",
  414.   "vertical", "single-column", 0
  415. };
  416.  
  417. static enum format const formats[] =
  418. {
  419.   long_format, long_format, with_commas, horizontal, horizontal,
  420.   many_per_line, one_per_line
  421. };
  422.  
  423. static char const* const sort_args[] =
  424. {
  425.   "none", "time", "size", "extension", 0
  426. };
  427.  
  428. static enum sort_type const sort_types[] =
  429. {
  430.   sort_none, sort_time, sort_size, sort_extension
  431. };
  432.  
  433. static char const* const time_args[] =
  434. {
  435.   "atime", "access", "use", "ctime", "status", 0
  436. };
  437.  
  438. static enum time_type const time_types[] =
  439. {
  440.   time_atime, time_atime, time_atime, time_ctime, time_ctime
  441. };
  442.  
  443.  
  444. main (argc, argv)
  445.      int argc;
  446.      char **argv;
  447. {
  448.   register int i;
  449.   register struct pending *thispend;
  450.  
  451.   exit_status = 0;
  452.   dir_defaulted = 1;
  453.   print_dir_name = 1;
  454.   pending_dirs = 0;
  455.   current_time = time ((time_t *) 0);
  456.  
  457.   program_name = argv[0];
  458.   i = decode_switches (argc, argv);
  459.  
  460.   if (show_version)
  461.     {
  462.       printf ("%s\n", version_string);
  463.       exit (0);
  464.     }
  465.  
  466.   if (show_help)
  467.     usage (0);
  468.  
  469.   format_needs_stat = sort_type == sort_time || sort_type == sort_size
  470.     || format == long_format
  471.     || trace_links || trace_dirs || indicator_style != none
  472.     || print_block_size || print_inode;
  473.  
  474.   nfiles = 100;
  475.   files = (struct file *) xmalloc (sizeof (struct file) * nfiles);
  476.   files_index = 0;
  477.  
  478.   clear_files ();
  479.  
  480.   if (i < argc)
  481.     dir_defaulted = 0;
  482.   for (; i < argc; i++)
  483.     gobble_file (argv[i], 1, "");
  484.  
  485.   if (dir_defaulted)
  486.     {
  487.       if (immediate_dirs)
  488.     gobble_file (".", 1, "");
  489.       else
  490.     queue_directory (".", 0);
  491.     }
  492.  
  493.   if (files_index)
  494.     {
  495.       sort_files ();
  496.       if (!immediate_dirs)
  497.     extract_dirs_from_files ("", 0);
  498.       /* `files_index' might be zero now.  */
  499.     }
  500.   if (files_index)
  501.     {
  502.       print_current_files ();
  503.       if (pending_dirs)
  504.     putchar ('\n');
  505.     }
  506.   else if (pending_dirs && pending_dirs->next == 0)
  507.     print_dir_name = 0;
  508.  
  509.   while (pending_dirs)
  510.     {
  511.       thispend = pending_dirs;
  512.       pending_dirs = pending_dirs->next;
  513.       print_dir (thispend->name, thispend->realname);
  514.       free (thispend->name);
  515.       if (thispend->realname)
  516.     free (thispend->realname);
  517.       free (thispend);
  518.       print_dir_name = 1;
  519.     }
  520.  
  521.   exit (exit_status);
  522. }
  523.  
  524. /* Set all the option flags according to the switches specified.
  525.    Return the index of the first non-option argument.  */
  526.  
  527. static int
  528. decode_switches (argc, argv)
  529.      int argc;
  530.      char **argv;
  531. {
  532.   register char *p;
  533.   int c;
  534.   int i;
  535.  
  536.   qmark_funny_chars = 0;
  537.   quote_funny_chars = 0;
  538.  
  539.   /* initialize all switches to default settings */
  540.  
  541.   switch (ls_mode)
  542.     {
  543.     case LS_MULTI_COL:
  544.       /* This is for the `dir' program.  */
  545.       format = many_per_line;
  546.       quote_funny_chars = 1;
  547.       break;
  548.  
  549.     case LS_LONG_FORMAT:
  550.       /* This is for the `vdir' program.  */
  551.       format = long_format;
  552.       quote_funny_chars = 1;
  553.       break;
  554.  
  555.     case LS_LS:
  556.       /* This is for the `ls' program.  */
  557.       if (isatty (1))
  558.     {
  559.       format = many_per_line;
  560.       qmark_funny_chars = 1;
  561.     }
  562.       else
  563.     {
  564.       format = one_per_line;
  565.       qmark_funny_chars = 0;
  566.     }
  567.       break;
  568.  
  569.     default:
  570.       abort ();
  571.     }
  572.  
  573.   time_type = time_mtime;
  574.   full_time = 0;
  575.   sort_type = sort_name;
  576.   sort_reverse = 0;
  577.   numeric_users = 0;
  578.   print_block_size = 0;
  579.   kilobyte_blocks = getenv ("POSIXLY_CORRECT") == 0;
  580.   indicator_style = none;
  581.   print_inode = 0;
  582.   trace_links = 0;
  583.   trace_dirs = 0;
  584.   immediate_dirs = 0;
  585.   all_files = 0;
  586.   really_all_files = 0;
  587.   ignore_patterns = 0;
  588.   quote_as_string = 0;
  589.  
  590.   p = getenv ("COLUMNS");
  591.   line_length = p ? atoi (p) : 80;
  592.  
  593. #ifdef TIOCGWINSZ
  594.   {
  595.     struct winsize ws;
  596.  
  597.     if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
  598.       line_length = ws.ws_col;
  599.   }
  600. #endif
  601.  
  602.   p = getenv ("TABSIZE");
  603.   tabsize = p ? atoi (p) : 8;
  604.  
  605.   while ((c = getopt_long (argc, argv, "abcdfgiklmnpqrstuw:xABCFGI:LNQRST:UX1",
  606.                long_options, (int *) 0)) != EOF)
  607.     {
  608.       switch (c)
  609.     {
  610.     case 0:
  611.       break;
  612.  
  613.     case 'a':
  614.       all_files = 1;
  615.       really_all_files = 1;
  616.       break;
  617.  
  618.     case 'b':
  619.       quote_funny_chars = 1;
  620.       qmark_funny_chars = 0;
  621.       break;
  622.  
  623.     case 'c':
  624.       time_type = time_ctime;
  625.       break;
  626.  
  627.     case 'd':
  628.       immediate_dirs = 1;
  629.       break;
  630.  
  631.     case 'f':
  632.       /* Same as enabling -a -U and disabling -l -s.  */
  633.       all_files = 1;
  634.       really_all_files = 1;
  635.       sort_type = sort_none;
  636.       /* disable -l */
  637.       if (format == long_format)
  638.         format = (isatty (1) ? many_per_line : one_per_line);
  639.       print_block_size = 0;  /* disable -s */
  640.       break;
  641.  
  642.     case 'g':
  643.       /* No effect.  For BSD compatibility. */
  644.       break;
  645.  
  646.     case 'i':
  647.       print_inode = 1;
  648.       break;
  649.  
  650.     case 'k':
  651.       kilobyte_blocks = 1;
  652.       break;
  653.  
  654.     case 'l':
  655.       format = long_format;
  656.       break;
  657.  
  658.     case 'm':
  659.       format = with_commas;
  660.       break;
  661.  
  662.     case 'n':
  663.       numeric_users = 1;
  664.       break;
  665.  
  666.     case 'p':
  667.       indicator_style = not_programs;
  668.       break;
  669.  
  670.     case 'q':
  671.       qmark_funny_chars = 1;
  672.       quote_funny_chars = 0;
  673.       break;
  674.  
  675.     case 'r':
  676.       sort_reverse = 1;
  677.       break;
  678.  
  679.     case 's':
  680.       print_block_size = 1;
  681.       break;
  682.  
  683.     case 't':
  684.       sort_type = sort_time;
  685.       break;
  686.  
  687.     case 'u':
  688.       time_type = time_atime;
  689.       break;
  690.  
  691.     case 'w':
  692.       line_length = atoi (optarg);
  693.       if (line_length < 1)
  694.         error (1, 0, "invalid line width: %s", optarg);
  695.       break;
  696.  
  697.     case 'x':
  698.       format = horizontal;
  699.       break;
  700.  
  701.     case 'A':
  702.       all_files = 1;
  703.       break;
  704.  
  705.     case 'B':
  706. #ifdef AMIGA
  707.       add_ignore_pattern ("*!");
  708.       add_ignore_pattern (".*!");
  709. #else
  710.       add_ignore_pattern ("*~");
  711.       add_ignore_pattern (".*~");
  712. #endif
  713.       break;
  714.  
  715.     case 'C':
  716.       format = many_per_line;
  717.       break;
  718.  
  719.     case 'F':
  720.       indicator_style = all;
  721.       break;
  722.  
  723.     case 'G':        /* inhibit display of group info */
  724.       inhibit_group = 1;
  725.       break;
  726.  
  727.     case 'I':
  728.       add_ignore_pattern (optarg);
  729.       break;
  730.  
  731.     case 'L':
  732.       trace_links = 1;
  733.       break;
  734.  
  735.     case 'N':
  736.       quote_funny_chars = 0;
  737.       qmark_funny_chars = 0;
  738.       break;
  739.  
  740.     case 'Q':
  741.       quote_as_string = 1;
  742.       quote_funny_chars = 1;
  743.       qmark_funny_chars = 0;
  744.       break;
  745.  
  746.     case 'R':
  747.       trace_dirs = 1;
  748.       break;
  749.  
  750.     case 'S':
  751.       sort_type = sort_size;
  752.       break;
  753.  
  754.     case 'T':
  755.       tabsize = atoi (optarg);
  756.       if (tabsize < 1)
  757.         error (1, 0, "invalid tab size: %s", optarg);
  758.       break;
  759.  
  760.     case 'U':
  761.       sort_type = sort_none;
  762.       break;
  763.  
  764.     case 'X':
  765.       sort_type = sort_extension;
  766.       break;
  767.  
  768.     case '1':
  769.       format = one_per_line;
  770.       break;
  771.  
  772.     case 10:        /* +sort */
  773.       i = argmatch (optarg, sort_args);
  774.       if (i < 0)
  775.         {
  776.           invalid_arg ("sort type", optarg, i);
  777.           usage (1);
  778.         }
  779.       sort_type = sort_types[i];
  780.       break;
  781.  
  782.     case 11:        /* +time */
  783.       i = argmatch (optarg, time_args);
  784.       if (i < 0)
  785.         {
  786.           invalid_arg ("time type", optarg, i);
  787.           usage (1);
  788.         }
  789.       time_type = time_types[i];
  790.       break;
  791.  
  792.     case 12:        /* +format */
  793.       i = argmatch (optarg, format_args);
  794.       if (i < 0)
  795.         {
  796.           invalid_arg ("format type", optarg, i);
  797.           usage (1);
  798.         }
  799.       format = formats[i];
  800.       break;
  801.  
  802.     default:
  803.       usage (1);
  804.     }
  805.     }
  806.  
  807.   return optind;
  808. }
  809.  
  810. /* Request that the directory named `name' have its contents listed later.
  811.    If `realname' is nonzero, it will be used instead of `name' when the
  812.    directory name is printed.  This allows symbolic links to directories
  813.    to be treated as regular directories but still be listed under their
  814.    real names. */
  815.  
  816. static void
  817. queue_directory (name, realname)
  818.      char *name;
  819.      char *realname;
  820. {
  821.   struct pending *new;
  822.  
  823.   new = (struct pending *) xmalloc (sizeof (struct pending));
  824.   new->next = pending_dirs;
  825.   pending_dirs = new;
  826.   new->name = xstrdup (name);
  827.   if (realname)
  828.     new->realname = xstrdup (realname);
  829.   else
  830.     new->realname = 0;
  831. }
  832.  
  833. /* Read directory `name', and list the files in it.
  834.    If `realname' is nonzero, print its name instead of `name';
  835.    this is used for symbolic links to directories. */
  836.  
  837. static void
  838. print_dir (name, realname)
  839.      char *name;
  840.      char *realname;
  841. {
  842.   register DIR *reading;
  843.   register struct dirent *next;
  844.   register int total_blocks = 0;
  845.  
  846.   errno = 0;
  847.   reading = opendir (name);
  848.   if (!reading)
  849.     {
  850.       error (0, errno, "%s", name);
  851.       exit_status = 1;
  852.       return;
  853.     }
  854.  
  855.   /* Read the directory entries, and insert the subfiles into the `files'
  856.      table.  */
  857.  
  858.   clear_files ();
  859.  
  860.   while ((next = readdir (reading)) != NULL)
  861.     if (file_interesting (next))
  862.       total_blocks += gobble_file (next->d_name, 0, name);
  863.  
  864.   if (CLOSEDIR (reading))
  865.     {
  866.       error (0, errno, "%s", name);
  867.       exit_status = 1;
  868.       /* Don't return; print whatever we got. */
  869.     }
  870.  
  871.   /* Sort the directory contents.  */
  872.   sort_files ();
  873.  
  874.   /* If any member files are subdirectories, perhaps they should have their
  875.      contents listed rather than being mentioned here as files.  */
  876.  
  877.   if (trace_dirs)
  878.     extract_dirs_from_files (name, 1);
  879.  
  880.   if (print_dir_name)
  881.     {
  882.       if (realname)
  883.     printf ("%s:\n", realname);
  884.       else
  885.     printf ("%s:\n", name);
  886.     }
  887.  
  888.   if (format == long_format || print_block_size)
  889.     printf ("total %u\n", total_blocks);
  890.  
  891.   if (files_index)
  892.     print_current_files ();
  893.  
  894.   if (pending_dirs)
  895.     putchar ('\n');
  896. }
  897.  
  898. /* Add `pattern' to the list of patterns for which files that match are
  899.    not listed.  */
  900.  
  901. static void
  902. add_ignore_pattern (pattern)
  903.      char *pattern;
  904. {
  905.   register struct ignore_pattern *ignore;
  906.  
  907.   ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
  908.   ignore->pattern = pattern;
  909.   /* Add it to the head of the linked list. */
  910.   ignore->next = ignore_patterns;
  911.   ignore_patterns = ignore;
  912. }
  913.  
  914. /* Return nonzero if the file in `next' should be listed. */
  915.  
  916. static int
  917. file_interesting (next)
  918.      register struct dirent *next;
  919. {
  920.   register struct ignore_pattern *ignore;
  921.  
  922.   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
  923.     if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
  924.       return 0;
  925.  
  926.   if (really_all_files
  927.       || next->d_name[0] != '.'
  928.       || (all_files
  929.       && next->d_name[1] != '\0'
  930.       && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
  931.     return 1;
  932.  
  933.   return 0;
  934. }
  935.  
  936. /* Enter and remove entries in the table `files'.  */
  937.  
  938. /* Empty the table of files. */
  939.  
  940. static void
  941. clear_files ()
  942. {
  943.   register int i;
  944.  
  945.   for (i = 0; i < files_index; i++)
  946.     {
  947.       free (files[i].name);
  948.       if (files[i].linkname)
  949.     free (files[i].linkname);
  950.     }
  951.  
  952.   files_index = 0;
  953.   block_size_size = 4;
  954. }
  955.  
  956. /* Add a file to the current table of files.
  957.    Verify that the file exists, and print an error message if it does not.
  958.    Return the number of blocks that the file occupies.  */
  959.  
  960. static int
  961. gobble_file (name, explicit_arg, dirname)
  962.      char *name;
  963.      int explicit_arg;
  964.      char *dirname;
  965. {
  966.   register int blocks;
  967.   register int val;
  968.   register char *path;
  969.  
  970.   if (files_index == nfiles)
  971.     {
  972.       nfiles *= 2;
  973.       files = (struct file *) xrealloc (files, sizeof (struct file) * nfiles);
  974.     }
  975.  
  976.   files[files_index].linkname = 0;
  977.   files[files_index].linkmode = 0;
  978.  
  979.   if (explicit_arg || format_needs_stat)
  980.     {
  981.       /* `path' is the absolute pathname of this file. */
  982.  
  983.       if (name[0] == '/' || dirname[0] == 0)
  984.     path = name;
  985.       else
  986.     {
  987.       path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
  988.       attach (path, dirname, name);
  989.     }
  990.  
  991.       if (trace_links)
  992.     {
  993.       val = stat (path, &files[files_index].stat);
  994.       if (val < 0)
  995.         /* Perhaps a symbolically-linked to file doesn't exist; stat
  996.            the link instead. */
  997.         val = lstat (path, &files[files_index].stat);
  998.     }
  999.       else
  1000.     val = lstat (path, &files[files_index].stat);
  1001.       if (val < 0)
  1002.     {
  1003.       error (0, errno, "%s", path);
  1004.       exit_status = 1;
  1005.       return 0;
  1006.     }
  1007.  
  1008. #ifdef S_ISLNK
  1009.       if (S_ISLNK (files[files_index].stat.st_mode)
  1010.       && (explicit_arg || format == long_format))
  1011.     {
  1012.       char *linkpath;
  1013.       struct stat linkstats;
  1014.  
  1015.       get_link_name (path, &files[files_index]);
  1016.       linkpath = make_link_path (path, files[files_index].linkname);
  1017.  
  1018.       /* Avoid following symbolic links when possible, ie, when
  1019.          they won't be traced and when no indicator is needed. */
  1020.       if (linkpath
  1021.           && ((explicit_arg && format != long_format)
  1022.            || indicator_style != none)
  1023.           && stat (linkpath, &linkstats) == 0)
  1024.         {
  1025.           /* Symbolic links to directories that are mentioned on the
  1026.          command line are automatically traced if not being
  1027.          listed as files.  */
  1028.           if (explicit_arg && format != long_format
  1029.           && S_ISDIR (linkstats.st_mode))
  1030.         {
  1031.           /* Substitute the linked-to directory's name, but
  1032.              save the real name in `linkname' for printing.  */
  1033.           if (!immediate_dirs)
  1034.             {
  1035.               char *tempname = name;
  1036.               name = linkpath;
  1037.               linkpath = files[files_index].linkname;
  1038.               files[files_index].linkname = tempname;
  1039.             }
  1040.           files[files_index].stat = linkstats;
  1041.         }
  1042.           else
  1043.         /* Get the linked-to file's mode for the filetype indicator
  1044.            in long listings.  */
  1045.         files[files_index].linkmode = linkstats.st_mode;
  1046.         }
  1047.       if (linkpath)
  1048.         free (linkpath);
  1049.     }
  1050. #endif
  1051.  
  1052. #ifdef S_ISLNK
  1053.       if (S_ISLNK (files[files_index].stat.st_mode))
  1054.     files[files_index].filetype = symbolic_link;
  1055.       else
  1056. #endif
  1057.     if (S_ISDIR (files[files_index].stat.st_mode))
  1058.       {
  1059.         if (explicit_arg && !immediate_dirs)
  1060.           files[files_index].filetype = arg_directory;
  1061.         else
  1062.           files[files_index].filetype = directory;
  1063.       }
  1064.     else
  1065.       files[files_index].filetype = normal;
  1066.  
  1067.       blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
  1068.                    kilobyte_blocks);
  1069.       if (blocks >= 10000 && block_size_size < 5)
  1070.     block_size_size = 5;
  1071.       if (blocks >= 100000 && block_size_size < 6)
  1072.     block_size_size = 6;
  1073.       if (blocks >= 1000000 && block_size_size < 7)
  1074.     block_size_size = 7;
  1075.     }
  1076.   else
  1077.     blocks = 0;
  1078.  
  1079.   files[files_index].name = xstrdup (name);
  1080.   files_index++;
  1081.  
  1082.   return blocks;
  1083. }
  1084.  
  1085. #ifdef S_ISLNK
  1086.  
  1087. /* Put the name of the file that `filename' is a symbolic link to
  1088.    into the `linkname' field of `f'. */
  1089.  
  1090. static void
  1091. get_link_name (filename, f)
  1092.      char *filename;
  1093.      struct file *f;
  1094. {
  1095.   char *linkbuf;
  1096.   register int linksize;
  1097.  
  1098.   linkbuf = (char *) alloca (PATH_MAX + 2);
  1099.   /* Some automounters give incorrect st_size for mount points.
  1100.      I can't think of a good workaround for it, though.  */
  1101.   linksize = readlink (filename, linkbuf, PATH_MAX + 1);
  1102.   if (linksize < 0)
  1103.     {
  1104.       error (0, errno, "%s", filename);
  1105.       exit_status = 1;
  1106.     }
  1107.   else
  1108.     {
  1109.       linkbuf[linksize] = '\0';
  1110.       f->linkname = xstrdup (linkbuf);
  1111.     }
  1112. }
  1113.  
  1114. /* If `linkname' is a relative path and `path' contains one or more
  1115.    leading directories, return `linkname' with those directories
  1116.    prepended; otherwise, return a copy of `linkname'.
  1117.    If `linkname' is zero, return zero. */
  1118.  
  1119. static char *
  1120. make_link_path (path, linkname)
  1121.      char *path;
  1122.      char *linkname;
  1123. {
  1124.   char *linkbuf;
  1125.   int bufsiz;
  1126.  
  1127.   if (linkname == 0)
  1128.     return 0;
  1129.  
  1130.   if (*linkname == '/')
  1131.     return xstrdup (linkname);
  1132.  
  1133.   /* The link is to a relative path.  Prepend any leading path
  1134.      in `path' to the link name. */
  1135.   linkbuf = rindex (path, '/');
  1136.   if (linkbuf == 0)
  1137.     return xstrdup (linkname);
  1138.  
  1139.   bufsiz = linkbuf - path + 1;
  1140.   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
  1141.   strncpy (linkbuf, path, bufsiz);
  1142.   strcpy (linkbuf + bufsiz, linkname);
  1143.   return linkbuf;
  1144. }
  1145. #endif
  1146.  
  1147. /* Remove any entries from `files' that are for directories,
  1148.    and queue them to be listed as directories instead.
  1149.    `dirname' is the prefix to prepend to each dirname
  1150.    to make it correct relative to ls's working dir.
  1151.    `recursive' is nonzero if we should not treat `.' and `..' as dirs.
  1152.    This is desirable when processing directories recursively.  */
  1153.  
  1154. static void
  1155. extract_dirs_from_files (dirname, recursive)
  1156.      char *dirname;
  1157.      int recursive;
  1158. {
  1159.   register int i, j;
  1160.   register char *path;
  1161.   int dirlen;
  1162.  
  1163.   dirlen = strlen (dirname) + 2;
  1164.   /* Queue the directories last one first, because queueing reverses the
  1165.      order.  */
  1166.   for (i = files_index - 1; i >= 0; i--)
  1167.     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
  1168.     && (!recursive || is_not_dot_or_dotdot (files[i].name)))
  1169.       {
  1170.     if (files[i].name[0] == '/' || dirname[0] == 0)
  1171.       {
  1172.         queue_directory (files[i].name, files[i].linkname);
  1173.       }
  1174.     else
  1175.       {
  1176.         path = (char *) xmalloc (strlen (files[i].name) + dirlen);
  1177.         attach (path, dirname, files[i].name);
  1178.         queue_directory (path, files[i].linkname);
  1179.         free (path);
  1180.       }
  1181.     if (files[i].filetype == arg_directory)
  1182.       free (files[i].name);
  1183.       }
  1184.  
  1185.   /* Now delete the directories from the table, compacting all the remaining
  1186.      entries.  */
  1187.  
  1188.   for (i = 0, j = 0; i < files_index; i++)
  1189.     if (files[i].filetype != arg_directory)
  1190.       files[j++] = files[i];
  1191.   files_index = j;
  1192. }
  1193.  
  1194. /* Return non-zero if `name' doesn't end in `.' or `..'
  1195.    This is so we don't try to recurse on `././././. ...' */
  1196.  
  1197. static int
  1198. is_not_dot_or_dotdot (name)
  1199.      char *name;
  1200. {
  1201.   char *t;
  1202.  
  1203.   t = rindex (name, '/');
  1204.   if (t)
  1205.     name = t + 1;
  1206.  
  1207.   if (name[0] == '.'
  1208.       && (name[1] == '\0'
  1209.       || (name[1] == '.' && name[2] == '\0')))
  1210.     return 0;
  1211.  
  1212.   return 1;
  1213. }
  1214.  
  1215. /* Sort the files now in the table.  */
  1216.  
  1217. static void
  1218. sort_files ()
  1219. {
  1220.   int (*func) ();
  1221.  
  1222.   switch (sort_type)
  1223.     {
  1224.     case sort_none:
  1225.       return;
  1226.     case sort_time:
  1227.       switch (time_type)
  1228.     {
  1229.     case time_ctime:
  1230.       func = sort_reverse ? rev_cmp_ctime : compare_ctime;
  1231.       break;
  1232.     case time_mtime:
  1233.       func = sort_reverse ? rev_cmp_mtime : compare_mtime;
  1234.       break;
  1235.     case time_atime:
  1236.       func = sort_reverse ? rev_cmp_atime : compare_atime;
  1237.       break;
  1238.     default:
  1239.       abort ();
  1240.     }
  1241.       break;
  1242.     case sort_name:
  1243.       func = sort_reverse ? rev_cmp_name : compare_name;
  1244.       break;
  1245.     case sort_extension:
  1246.       func = sort_reverse ? rev_cmp_extension : compare_extension;
  1247.       break;
  1248.     case sort_size:
  1249.       func = sort_reverse ? rev_cmp_size : compare_size;
  1250.       break;
  1251.     default:
  1252.       abort ();
  1253.     }
  1254.  
  1255.   qsort (files, files_index, sizeof (struct file), func);
  1256. }
  1257.  
  1258. /* Comparison routines for sorting the files. */
  1259.  
  1260. static int
  1261. compare_ctime (file1, file2)
  1262.      struct file *file1, *file2;
  1263. {
  1264.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1265. }
  1266.  
  1267. static int
  1268. rev_cmp_ctime (file2, file1)
  1269.      struct file *file1, *file2;
  1270. {
  1271.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1272. }
  1273.  
  1274. static int
  1275. compare_mtime (file1, file2)
  1276.      struct file *file1, *file2;
  1277. {
  1278.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1279. }
  1280.  
  1281. static int
  1282. rev_cmp_mtime (file2, file1)
  1283.      struct file *file1, *file2;
  1284. {
  1285.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1286. }
  1287.  
  1288. static int
  1289. compare_atime (file1, file2)
  1290.      struct file *file1, *file2;
  1291. {
  1292.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1293. }
  1294.  
  1295. static int
  1296. rev_cmp_atime (file2, file1)
  1297.      struct file *file1, *file2;
  1298. {
  1299.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1300. }
  1301.  
  1302. static int
  1303. compare_size (file1, file2)
  1304.      struct file *file1, *file2;
  1305. {
  1306.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1307. }
  1308.  
  1309. static int
  1310. rev_cmp_size (file2, file1)
  1311.      struct file *file1, *file2;
  1312. {
  1313.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1314. }
  1315.  
  1316. static int
  1317. compare_name (file1, file2)
  1318.      struct file *file1, *file2;
  1319. {
  1320.   return strcmp (file1->name, file2->name);
  1321. }
  1322.  
  1323. static int
  1324. rev_cmp_name (file2, file1)
  1325.      struct file *file1, *file2;
  1326. {
  1327.   return strcmp (file1->name, file2->name);
  1328. }
  1329.  
  1330. /* Compare file extensions.  Files with no extension are `smallest'.
  1331.    If extensions are the same, compare by filenames instead. */
  1332.  
  1333. static int
  1334. compare_extension (file1, file2)
  1335.      struct file *file1, *file2;
  1336. {
  1337.   register char *base1, *base2;
  1338.   register int cmp;
  1339.  
  1340.   base1 = rindex (file1->name, '.');
  1341.   base2 = rindex (file2->name, '.');
  1342.   if (base1 == 0 && base2 == 0)
  1343.     return strcmp (file1->name, file2->name);
  1344.   if (base1 == 0)
  1345.     return -1;
  1346.   if (base2 == 0)
  1347.     return 1;
  1348.   cmp = strcmp (base1, base2);
  1349.   if (cmp == 0)
  1350.     return strcmp (file1->name, file2->name);
  1351.   return cmp;
  1352. }
  1353.  
  1354. static int
  1355. rev_cmp_extension (file2, file1)
  1356.      struct file *file1, *file2;
  1357. {
  1358.   register char *base1, *base2;
  1359.   register int cmp;
  1360.  
  1361.   base1 = rindex (file1->name, '.');
  1362.   base2 = rindex (file2->name, '.');
  1363.   if (base1 == 0 && base2 == 0)
  1364.     return strcmp (file1->name, file2->name);
  1365.   if (base1 == 0)
  1366.     return -1;
  1367.   if (base2 == 0)
  1368.     return 1;
  1369.   cmp = strcmp (base1, base2);
  1370.   if (cmp == 0)
  1371.     return strcmp (file1->name, file2->name);
  1372.   return cmp;
  1373. }
  1374.  
  1375. /* List all the files now in the table.  */
  1376.  
  1377. static void
  1378. print_current_files ()
  1379. {
  1380.   register int i;
  1381.  
  1382.   switch (format)
  1383.     {
  1384.     case one_per_line:
  1385.       for (i = 0; i < files_index; i++)
  1386.     {
  1387.       print_file_name_and_frills (files + i);
  1388.       putchar ('\n');
  1389.     }
  1390.       break;
  1391.  
  1392.     case many_per_line:
  1393.       print_many_per_line ();
  1394.       break;
  1395.  
  1396.     case horizontal:
  1397.       print_horizontal ();
  1398.       break;
  1399.  
  1400.     case with_commas:
  1401.       print_with_commas ();
  1402.       break;
  1403.  
  1404.     case long_format:
  1405.       for (i = 0; i < files_index; i++)
  1406.     {
  1407.       print_long_format (files + i);
  1408.       putchar ('\n');
  1409.     }
  1410.       break;
  1411.     }
  1412. }
  1413.  
  1414. static void
  1415. print_long_format (f)
  1416.      struct file *f;
  1417. {
  1418.   char modebuf[20];
  1419.   char timebuf[40];
  1420.   time_t when;
  1421.  
  1422.   mode_string (f->stat.st_mode, modebuf);
  1423.   modebuf[10] = 0;
  1424.  
  1425.   switch (time_type)
  1426.     {
  1427.     case time_ctime:
  1428.       when = f->stat.st_ctime;
  1429.       break;
  1430.     case time_mtime:
  1431.       when = f->stat.st_mtime;
  1432.       break;
  1433.     case time_atime:
  1434.       when = f->stat.st_atime;
  1435.       break;
  1436.     }
  1437.  
  1438.   strcpy (timebuf, ctime (&when));
  1439.  
  1440.   if (full_time)
  1441.     timebuf[24] = '\0';
  1442.   else
  1443.     {
  1444.       if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
  1445.       || current_time < when - 60L * 60L) /* In the future. */
  1446.     {
  1447.       /* The file is fairly old or in the future.
  1448.          POSIX says the cutoff is 6 months old;
  1449.          approximate this by 6*30 days.
  1450.          Allow a 1 hour slop factor for what is considered "the future",
  1451.          to allow for NFS server/client clock disagreement.
  1452.          Show the year instead of the time of day.  */
  1453.       strcpy (timebuf + 11, timebuf + 19);
  1454.     }
  1455.       timebuf[16] = 0;
  1456.     }
  1457.  
  1458.   if (print_inode)
  1459.     printf ("%6lu ", (unsigned long) f->stat.st_ino);
  1460.  
  1461.   if (print_block_size)
  1462.     printf ("%*u ", block_size_size,
  1463.         (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
  1464.                         kilobyte_blocks));
  1465.  
  1466.   /* The space between the mode and the number of links is the POSIX
  1467.      "optional alternate access method flag". */
  1468.   printf ("%s %3u ", modebuf, f->stat.st_nlink);
  1469.  
  1470.   if (numeric_users)
  1471.     printf ("%-8u ", (unsigned int) f->stat.st_uid);
  1472.   else
  1473.     printf ("%-8.8s ", getuser (f->stat.st_uid));
  1474.  
  1475.   if (!inhibit_group)
  1476.     {
  1477.       if (numeric_users)
  1478.     printf ("%-8u ", (unsigned int) f->stat.st_gid);
  1479.       else
  1480.     printf ("%-8.8s ", getgroup (f->stat.st_gid));
  1481.     }
  1482.  
  1483.   if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
  1484.     printf ("%3u, %3u ", (unsigned) major (f->stat.st_rdev),
  1485.         (unsigned) minor (f->stat.st_rdev));
  1486.   else
  1487.     printf ("%8lu ", f->stat.st_size);
  1488.  
  1489.   printf ("%s ", full_time ? timebuf : timebuf + 4);
  1490.  
  1491.   print_name_with_quoting (f->name);
  1492.  
  1493.   if (f->filetype == symbolic_link)
  1494.     {
  1495.       if (f->linkname)
  1496.     {
  1497.       fputs (" -> ", stdout);
  1498.       print_name_with_quoting (f->linkname);
  1499.       if (indicator_style != none)
  1500.         print_type_indicator (f->linkmode);
  1501.     }
  1502.     }
  1503.   else if (indicator_style != none)
  1504.     print_type_indicator (f->stat.st_mode);
  1505. }
  1506.  
  1507. static void
  1508. print_name_with_quoting (p)
  1509.      register char *p;
  1510. {
  1511.   register unsigned char c;
  1512.  
  1513.   if (quote_as_string)
  1514.     putchar ('"');
  1515.  
  1516.   while ((c = *p++))
  1517.     {
  1518.       if (quote_funny_chars)
  1519.     {
  1520.       switch (c)
  1521.         {
  1522.         case '\\':
  1523.           printf ("\\\\");
  1524.           break;
  1525.  
  1526.         case '\n':
  1527.           printf ("\\n");
  1528.           break;
  1529.  
  1530.         case '\b':
  1531.           printf ("\\b");
  1532.           break;
  1533.  
  1534.         case '\r':
  1535.           printf ("\\r");
  1536.           break;
  1537.  
  1538.         case '\t':
  1539.           printf ("\\t");
  1540.           break;
  1541.  
  1542.         case '\f':
  1543.           printf ("\\f");
  1544.           break;
  1545.  
  1546.         case ' ':
  1547.           printf ("\\ ");
  1548.           break;
  1549.  
  1550.         case '"':
  1551.           printf ("\\\"");
  1552.           break;
  1553.  
  1554.         default:
  1555.           if (c > 040 && c < 0177)
  1556.         putchar (c);
  1557.           else
  1558.         printf ("\\%03o", (unsigned int) c);
  1559.         }
  1560.     }
  1561.       else
  1562.     {
  1563.       if (c >= 040 && c < 0177)
  1564.         putchar (c);
  1565.       else if (!qmark_funny_chars)
  1566.         putchar (c);
  1567.       else
  1568.         putchar ('?');
  1569.     }
  1570.     }
  1571.  
  1572.   if (quote_as_string)
  1573.     putchar ('"');
  1574. }
  1575.  
  1576. /* Print the file name of `f' with appropriate quoting.
  1577.    Also print file size, inode number, and filetype indicator character,
  1578.    as requested by switches.  */
  1579.  
  1580. static void
  1581. print_file_name_and_frills (f)
  1582.      struct file *f;
  1583. {
  1584.   if (print_inode)
  1585.     printf ("%6lu ", (unsigned long) f->stat.st_ino);
  1586.  
  1587.   if (print_block_size)
  1588.     printf ("%*u ", block_size_size,
  1589.         (unsigned) convert_blocks (ST_NBLOCKS (f->stat),
  1590.                         kilobyte_blocks));
  1591.  
  1592.   print_name_with_quoting (f->name);
  1593.  
  1594.   if (indicator_style != none)
  1595.     print_type_indicator (f->stat.st_mode);
  1596. }
  1597.  
  1598. static void
  1599. print_type_indicator (mode)
  1600.      unsigned int mode;
  1601. {
  1602.   if (S_ISDIR (mode))
  1603.     putchar ('/');
  1604.  
  1605. #ifdef S_ISLNK
  1606.   if (S_ISLNK (mode))
  1607.     putchar ('@');
  1608. #endif
  1609.  
  1610. #ifdef S_ISFIFO
  1611.   if (S_ISFIFO (mode))
  1612.     putchar ('|');
  1613. #endif
  1614.  
  1615. #ifdef S_ISSOCK
  1616.   if (S_ISSOCK (mode))
  1617.     putchar ('=');
  1618. #endif
  1619.  
  1620.   if (S_ISREG (mode) && indicator_style == all
  1621.       && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1622.     putchar ('*');
  1623. }
  1624.  
  1625. static int
  1626. length_of_file_name_and_frills (f)
  1627.      struct file *f;
  1628. {
  1629.   register char *p = f->name;
  1630.   register char c;
  1631.   register int len = 0;
  1632.  
  1633.   if (print_inode)
  1634.     len += 7;
  1635.  
  1636.   if (print_block_size)
  1637.     len += 1 + block_size_size;
  1638.  
  1639.   if (quote_as_string)
  1640.     len += 2;
  1641.  
  1642.   while ((c = *p++))
  1643.     {
  1644.       if (quote_funny_chars)
  1645.     {
  1646.       switch (c)
  1647.         {
  1648.         case '\\':
  1649.         case '\n':
  1650.         case '\b':
  1651.         case '\r':
  1652.         case '\t':
  1653.         case '\f':
  1654.         case ' ':
  1655.           len += 2;
  1656.           break;
  1657.  
  1658.         case '"':
  1659.           if (quote_as_string)
  1660.         len += 2;
  1661.           else
  1662.         len += 1;
  1663.           break;
  1664.  
  1665.         default:
  1666.           if (c >= 040 && c < 0177)
  1667.         len += 1;
  1668.           else
  1669.         len += 4;
  1670.         }
  1671.     }
  1672.       else
  1673.     len += 1;
  1674.     }
  1675.  
  1676.   if (indicator_style != none)
  1677.     {
  1678.       unsigned filetype = f->stat.st_mode;
  1679.  
  1680.       if (S_ISREG (filetype))
  1681.     {
  1682.       if (indicator_style == all
  1683.           && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1684.         len += 1;
  1685.     }
  1686.       else if (S_ISDIR (filetype)
  1687. #ifdef S_ISLNK
  1688.            || S_ISLNK (filetype)
  1689. #endif
  1690. #ifdef S_ISFIFO
  1691.            || S_ISFIFO (filetype)
  1692. #endif
  1693. #ifdef S_ISSOCK
  1694.            || S_ISSOCK (filetype)
  1695. #endif
  1696.            )
  1697.     len += 1;
  1698.     }
  1699.  
  1700.   return len;
  1701. }
  1702.  
  1703. static void
  1704. print_many_per_line ()
  1705. {
  1706.   int filesno;            /* Index into files. */
  1707.   int row;            /* Current row. */
  1708.   int max_name_length;        /* Length of longest file name + frills. */
  1709.   int name_length;        /* Length of each file name + frills. */
  1710.   int pos;            /* Current character column. */
  1711.   int cols;            /* Number of files across. */
  1712.   int rows;            /* Maximum number of files down. */
  1713.  
  1714.   /* Compute the maximum file name length.  */
  1715.   max_name_length = 0;
  1716.   for (filesno = 0; filesno < files_index; filesno++)
  1717.     {
  1718.       name_length = length_of_file_name_and_frills (files + filesno);
  1719.       if (name_length > max_name_length)
  1720.     max_name_length = name_length;
  1721.     }
  1722.  
  1723.   /* Allow at least two spaces between names.  */
  1724.   max_name_length += 2;
  1725.  
  1726.   /* Calculate the maximum number of columns that will fit. */
  1727.   cols = line_length / max_name_length;
  1728.   if (cols == 0)
  1729.     cols = 1;
  1730.   /* Calculate the number of rows that will be in each column except possibly
  1731.      for a short column on the right. */
  1732.   rows = files_index / cols + (files_index % cols != 0);
  1733.   /* Recalculate columns based on rows. */
  1734.   cols = files_index / rows + (files_index % rows != 0);
  1735.  
  1736.   for (row = 0; row < rows; row++)
  1737.     {
  1738.       filesno = row;
  1739.       pos = 0;
  1740.       /* Print the next row.  */
  1741.       while (1)
  1742.     {
  1743.       print_file_name_and_frills (files + filesno);
  1744.       name_length = length_of_file_name_and_frills (files + filesno);
  1745.  
  1746.       filesno += rows;
  1747.       if (filesno >= files_index)
  1748.         break;
  1749.  
  1750.       indent (pos + name_length, pos + max_name_length);
  1751.       pos += max_name_length;
  1752.     }
  1753.       putchar ('\n');
  1754.     }
  1755. }
  1756.  
  1757. static void
  1758. print_horizontal ()
  1759. {
  1760.   int filesno;
  1761.   int max_name_length;
  1762.   int name_length;
  1763.   int cols;
  1764.   int pos;
  1765.  
  1766.   /* Compute the maximum file name length.  */
  1767.   max_name_length = 0;
  1768.   for (filesno = 0; filesno < files_index; filesno++)
  1769.     {
  1770.       name_length = length_of_file_name_and_frills (files + filesno);
  1771.       if (name_length > max_name_length)
  1772.     max_name_length = name_length;
  1773.     }
  1774.  
  1775.   /* Allow two spaces between names.  */
  1776.   max_name_length += 2;
  1777.  
  1778.   cols = line_length / max_name_length;
  1779.   if (cols == 0)
  1780.     cols = 1;
  1781.  
  1782.   pos = 0;
  1783.   name_length = 0;
  1784.  
  1785.   for (filesno = 0; filesno < files_index; filesno++)
  1786.     {
  1787.       if (filesno != 0)
  1788.     {
  1789.       if (filesno % cols == 0)
  1790.         {
  1791.           putchar ('\n');
  1792.           pos = 0;
  1793.         }
  1794.       else
  1795.         {
  1796.           indent (pos + name_length, pos + max_name_length);
  1797.           pos += max_name_length;
  1798.         }
  1799.     }
  1800.  
  1801.       print_file_name_and_frills (files + filesno);
  1802.  
  1803.       name_length = length_of_file_name_and_frills (files + filesno);
  1804.     }
  1805.   putchar ('\n');
  1806. }
  1807.  
  1808. static void
  1809. print_with_commas ()
  1810. {
  1811.   int filesno;
  1812.   int pos, old_pos;
  1813.  
  1814.   pos = 0;
  1815.  
  1816.   for (filesno = 0; filesno < files_index; filesno++)
  1817.     {
  1818.       old_pos = pos;
  1819.  
  1820.       pos += length_of_file_name_and_frills (files + filesno);
  1821.       if (filesno + 1 < files_index)
  1822.     pos += 2;        /* For the comma and space */
  1823.  
  1824.       if (old_pos != 0 && pos >= line_length)
  1825.     {
  1826.       putchar ('\n');
  1827.       pos -= old_pos;
  1828.     }
  1829.  
  1830.       print_file_name_and_frills (files + filesno);
  1831.       if (filesno + 1 < files_index)
  1832.     {
  1833.       putchar (',');
  1834.       putchar (' ');
  1835.     }
  1836.     }
  1837.   putchar ('\n');
  1838. }
  1839.  
  1840. /* Assuming cursor is at position FROM, indent up to position TO.  */
  1841.  
  1842. static void
  1843. indent (from, to)
  1844.      int from, to;
  1845. {
  1846.   while (from < to)
  1847.     {
  1848.       if (to / tabsize > from / tabsize)
  1849.     {
  1850.       putchar ('\t');
  1851.       from += tabsize - from % tabsize;
  1852.     }
  1853.       else
  1854.     {
  1855.       putchar (' ');
  1856.       from++;
  1857.     }
  1858.     }
  1859. }
  1860.  
  1861. /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
  1862.  
  1863. static void
  1864. attach (dest, dirname, name)
  1865.      char *dest, *dirname, *name;
  1866. {
  1867.   char *dirnamep = dirname;
  1868.  
  1869.   /* Copy dirname if it is not ".". */
  1870.   if (dirname[0] != '.' || dirname[1] != 0)
  1871.     {
  1872.       while (*dirnamep)
  1873.     *dest++ = *dirnamep++;
  1874.       /* Add '/' if `dirname' doesn't already end with it. */
  1875.       if (dirnamep > dirname && dirnamep[-1] != '/')
  1876.     *dest++ = '/';
  1877.     }
  1878.   while (*name)
  1879.     *dest++ = *name++;
  1880.   *dest = 0;
  1881. }
  1882.  
  1883. static void
  1884. usage (status)
  1885.      int status;
  1886. {
  1887.   if (status != 0)
  1888.     fprintf (stderr, "Try `%s --help' for more information.\n",
  1889.          program_name);
  1890.   else
  1891.     {
  1892.       printf ("Usage: %s [OPTION]... [PATH]...\n", program_name);
  1893.       printf ("\
  1894. \n\
  1895.   -a, --all                  do not hide entries starting with .\n\
  1896.   -b, --escape               print octal escapes for nongraphic characters\n\
  1897.   -c                         sort by change time; with -l: show ctime\n\
  1898.   -d, --directory            list directory entries instead of contents\n\
  1899.   -f                         do not sort, enable -aU, disable -lst\n\
  1900.   -g                         (ignored)\n\
  1901.   -i, --inode                print index number of each file\n\
  1902.   -k, --kilobytes            use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
  1903.   -l                         use a long listing format\n\
  1904.   -m                         fill width with a comma separated list of entries\n\
  1905.   -n, --numeric-uid-gid      list numeric UIDs and GIDs instead of names\n\
  1906.   -p                         append a character for typing each entry\n\
  1907.   -q, --hide-control-chars   print ? instead of non graphic characters\n\
  1908.   -r, --reverse              reverse order while sorting\n\
  1909.   -s, --size                 print block size of each file\n\
  1910.   -t                         sort by modification time; with -l: show mtime\n\
  1911.   -u                         sort by last access time; with -l: show atime\n\
  1912.   -w, --width COLS           assume screen width instead of current value\n\
  1913.   -x                         list entries by lines instead of by columns\n\
  1914.   -A, --almost-all           do not list implied . and ..\n");
  1915.  
  1916.       printf ("\
  1917.   -B, --ignore-backups       do not list implied entries ending with ~\n\
  1918.   -C                         list entries by columns\n\
  1919.   -F, --classify             append a character for typing each entry\n\
  1920.   -G, --no-group             inhibit display of group information\n\
  1921.   -I, --ignore PATTERN       do not list implied entries matching shell PATTERN\n\
  1922.   -L, --dereference          list entries pointed to by symbolic links\n\
  1923.   -N, --literal              do not quote entry names\n\
  1924.   -Q, --quote-name           enclose entry names in double quotes\n\
  1925.   -R, --recursive            list subdirectories recursively\n\
  1926.   -S                         sort by file size\n\
  1927.   -T, --tabsize COLS         assume tab stops at each COLS instead of 8\n\
  1928.   -U                         do not sort; list entries in directory order\n\
  1929.   -X                         sort alphabetically by entry extension\n\
  1930.   -1                         list one file per line\n\
  1931.       --full-time            list both full date and full time\n\
  1932.       --help                 display this help and exit\n\
  1933.       --format WORD          across -x, commas -m, horizontal -x, long -l,\n\
  1934.                                single-column -1, verbose -l, vertical -C\n\
  1935.       --sort WORD            ctime -c, extension -X, none -U, size -S,\n\
  1936.                                status -c, time -t\n\
  1937.       --time WORD            atime -u, access -u, use -u\n\
  1938.       --version              output version information and exit\n\
  1939. \n\
  1940. Sort entries alphabetically if none of -cftuSUX nor --sort.\n");
  1941.  
  1942.     }
  1943.   exit (status);
  1944. }
  1945.