home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / head.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  8.9 KB  |  413 lines

  1. /* head -- output first part of file(s)
  2.    Copyright (C) 1989, 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. /* Options:
  19.    -b            Print first N 512-byte blocks.
  20.    -c, --bytes=N[bkm]    Print first N bytes
  21.             [or 512-byte blocks, kilobytes, or megabytes].
  22.    -k            Print first N kilobytes.
  23.    -N, -l, -n, --lines=N    Print first N lines.
  24.    -m            Print first N megabytes.
  25.    -q, --quiet, --silent    Never print filename headers.
  26.    -v, --verbose        Always print filename headers.
  27.  
  28.    Reads from standard input if no files are given or when a filename of
  29.    ``-'' is encountered.
  30.    By default, filename headers are printed only if more than one file
  31.    is given.
  32.    By default, prints the first 10 lines (head -n 10).
  33.  
  34.    David MacKenzie <djm@gnu.ai.mit.edu> */
  35.  
  36. #include <config.h>
  37.  
  38. #include <stdio.h>
  39. #include <getopt.h>
  40. #include <sys/types.h>
  41. #include "system.h"
  42. #include "version.h"
  43.  
  44. /* Number of lines/chars/blocks to head. */
  45. #define DEFAULT_NUMBER 10
  46.  
  47. /* Size of atomic reads. */
  48. #define BUFSIZE (512 * 8)
  49.  
  50. /* Number of bytes per item we are printing.
  51.    If 0, head in lines. */
  52. static int unit_size;
  53.  
  54. /* If nonzero, print filename headers. */
  55. static int print_headers;
  56.  
  57. /* When to print the filename banners. */
  58. enum header_mode
  59. {
  60.   multiple_files, always, never
  61. };
  62.  
  63. void error ();
  64. int safe_read ();
  65.  
  66. static int head ();
  67. static int head_bytes ();
  68. static int head_file ();
  69. static int head_lines ();
  70. static long atou ();
  71. static void parse_unit ();
  72. static void usage ();
  73. static void write_header ();
  74.  
  75. /* The name this program was run with. */
  76. char *program_name;
  77.  
  78. /* Have we ever read standard input?  */
  79. static int have_read_stdin;
  80.  
  81. /* If non-zero, display usage information and exit.  */
  82. static int show_help;
  83.  
  84. /* If non-zero, print the version on standard output then exit.  */
  85. static int show_version;
  86.  
  87. static struct option const long_options[] =
  88. {
  89.   {"bytes", required_argument, NULL, 'c'},
  90.   {"lines", required_argument, NULL, 'n'},
  91.   {"quiet", no_argument, NULL, 'q'},
  92.   {"silent", no_argument, NULL, 'q'},
  93.   {"verbose", no_argument, NULL, 'v'},
  94.   {"help", no_argument, &show_help, 1},
  95.   {"version", no_argument, &show_version, 1},
  96.   {NULL, 0, NULL, 0}
  97. };
  98.  
  99. main (argc, argv)
  100.      int argc;
  101.      char **argv;
  102. {
  103.   enum header_mode header_mode = multiple_files;
  104.   int exit_status = 0;
  105.   long number = -1;        /* Number of items to print (-1 if undef.). */
  106.   int c;            /* Option character. */
  107.  
  108.   program_name = argv[0];
  109.   have_read_stdin = 0;
  110.   unit_size = 0;
  111.   print_headers = 0;
  112.  
  113.   if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
  114.     {
  115.       /* Old option syntax; a dash, one or more digits, and one or
  116.      more option letters.  Move past the number. */
  117.       for (number = 0, ++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
  118.     number = number * 10 + *argv[1] - '0';
  119.       /* Parse any appended option letters. */
  120.       while (*argv[1])
  121.     {
  122.       switch (*argv[1])
  123.         {
  124.         case 'b':
  125.           unit_size = 512;
  126.           break;
  127.  
  128.         case 'c':
  129.           unit_size = 1;
  130.           break;
  131.  
  132.         case 'k':
  133.           unit_size = 1024;
  134.           break;
  135.  
  136.         case 'l':
  137.           unit_size = 0;
  138.           break;
  139.  
  140.         case 'm':
  141.           unit_size = 1048576;
  142.           break;
  143.  
  144.         case 'q':
  145.           header_mode = never;
  146.           break;
  147.  
  148.         case 'v':
  149.           header_mode = always;
  150.           break;
  151.  
  152.         default:
  153.           error (0, 0, "unrecognized option `-%c'", *argv[1]);
  154.           usage (1);
  155.         }
  156.       ++argv[1];
  157.     }
  158.       /* Make the options we just parsed invisible to getopt. */
  159.       argv[1] = argv[0];
  160.       argv++;
  161.       argc--;
  162.     }
  163.  
  164.   while ((c = getopt_long (argc, argv, "c:n:qv", long_options, (int *) 0))
  165.      != EOF)
  166.     {
  167.       switch (c)
  168.     {
  169.     case 0:
  170.       break;
  171.  
  172.     case 'c':
  173.       unit_size = 1;
  174.       parse_unit (optarg);
  175.       goto getnum;
  176.     case 'n':
  177.       unit_size = 0;
  178.     getnum:
  179.       number = atou (optarg);
  180.       if (number == -1)
  181.         error (1, 0, "invalid number `%s'", optarg);
  182.       break;
  183.  
  184.     case 'q':
  185.       header_mode = never;
  186.       break;
  187.  
  188.     case 'v':
  189.       header_mode = always;
  190.       break;
  191.  
  192.     default:
  193.       usage (1);
  194.     }
  195.     }
  196.  
  197.   if (show_version)
  198.     {
  199.       printf ("head - %s\n", version_string);
  200.       exit (0);
  201.     }
  202.  
  203.   if (show_help)
  204.     usage (0);
  205.  
  206.   if (number == -1)
  207.     number = DEFAULT_NUMBER;
  208.  
  209.   if (unit_size > 1)
  210.     number *= unit_size;
  211.  
  212.   if (header_mode == always
  213.       || (header_mode == multiple_files && optind < argc - 1))
  214.     print_headers = 1;
  215.  
  216.   if (optind == argc)
  217.     exit_status |= head_file ("-", number);
  218.  
  219.   for (; optind < argc; ++optind)
  220.     exit_status |= head_file (argv[optind], number);
  221.  
  222.   if (have_read_stdin && close (0) < 0)
  223.     error (1, errno, "-");
  224.   if (fclose (stdout) == EOF)
  225.     error (1, errno, "write error");
  226.  
  227.   exit (exit_status);
  228. }
  229.  
  230. static int
  231. head_file (filename, number)
  232.      char *filename;
  233.      long number;
  234. {
  235.   int fd;
  236.  
  237.   if (!strcmp (filename, "-"))
  238.     {
  239.       have_read_stdin = 1;
  240.       filename = "standard input";
  241.       if (print_headers)
  242.     write_header (filename);
  243.       return head (filename, 0, number);
  244.     }
  245.   else
  246.     {
  247.       fd = open (filename, O_RDONLY);
  248.       if (fd >= 0)
  249.     {
  250.       int errors;
  251.  
  252.       if (print_headers)
  253.         write_header (filename);
  254.       errors = head (filename, fd, number);
  255.       if (close (fd) == 0)
  256.         return errors;
  257.     }
  258.       error (0, errno, "%s", filename);
  259.       return 1;
  260.     }
  261. }
  262.  
  263. static void
  264. write_header (filename)
  265.      char *filename;
  266. {
  267.   static int first_file = 1;
  268.  
  269.   printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
  270.   first_file = 0;
  271. }
  272.  
  273. static int
  274. head (filename, fd, number)
  275.      char *filename;
  276.      int fd;
  277.      long number;
  278. {
  279.   if (unit_size)
  280.     return head_bytes (filename, fd, number);
  281.   else
  282.     return head_lines (filename, fd, number);
  283. }
  284.  
  285. static int
  286. head_bytes (filename, fd, bytes_to_write)
  287.      char *filename;
  288.      int fd;
  289.      long bytes_to_write;
  290. {
  291.   char buffer[BUFSIZE];
  292.   int bytes_read;
  293.  
  294.   while (bytes_to_write)
  295.     {
  296.       bytes_read = safe_read (fd, buffer, BUFSIZE);
  297.       if (bytes_read < 0)
  298.     {
  299.       error (0, errno, "%s", filename);
  300.       return 1;
  301.     }
  302.       if (bytes_read == 0)
  303.     break;
  304.       if (bytes_read > bytes_to_write)
  305.     bytes_read = bytes_to_write;
  306.       if (fwrite (buffer, 1, bytes_read, stdout) == 0)
  307.     error (1, errno, "write error");
  308.       bytes_to_write -= bytes_read;
  309.     }
  310.   return 0;
  311. }
  312.  
  313. static int
  314. head_lines (filename, fd, lines_to_write)
  315.      char *filename;
  316.      int fd;
  317.      long lines_to_write;
  318. {
  319.   char buffer[BUFSIZE];
  320.   int bytes_read;
  321.   int bytes_to_write;
  322.  
  323.   while (lines_to_write)
  324.     {
  325.       bytes_read = safe_read (fd, buffer, BUFSIZE);
  326.       if (bytes_read < 0)
  327.     {
  328.       error (0, errno, "%s", filename);
  329.       return 1;
  330.     }
  331.       if (bytes_read == 0)
  332.     break;
  333.       bytes_to_write = 0;
  334.       while (bytes_to_write < bytes_read)
  335.     if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
  336.       break;
  337.       if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
  338.     error (1, errno, "write error");
  339.     }
  340.   return 0;
  341. }
  342.  
  343. static void
  344. parse_unit (str)
  345.      char *str;
  346. {
  347.   int arglen = strlen (str);
  348.  
  349.   if (arglen == 0)
  350.     return;
  351.  
  352.   switch (str[arglen - 1])
  353.     {
  354.     case 'b':
  355.       unit_size = 512;
  356.       str[arglen - 1] = '\0';
  357.       break;
  358.     case 'k':
  359.       unit_size = 1024;
  360.       str[arglen - 1] = '\0';
  361.       break;
  362.     case 'm':
  363.       unit_size = 1048576;
  364.       str[arglen - 1] = '\0';
  365.       break;
  366.     }
  367. }
  368.  
  369. /* Convert STR, a string of ASCII digits, into an unsigned integer.
  370.    Return -1 if STR does not represent a valid unsigned integer. */
  371.  
  372. static long
  373. atou (str)
  374.      char *str;
  375. {
  376.   int value;
  377.  
  378.   for (value = 0; ISDIGIT (*str); ++str)
  379.     value = value * 10 + *str - '0';
  380.   return *str ? -1 : value;
  381. }
  382.  
  383. static void
  384. usage (status)
  385.      int status;
  386. {
  387.   if (status != 0)
  388.     fprintf (stderr, "Try `%s --help' for more information.\n",
  389.          program_name);
  390.   else
  391.     {
  392.       printf ("\
  393. Usage: %s [OPTION]... [FILE]...\n\
  394. ",
  395.           program_name);
  396.       printf ("\
  397. \n\
  398.   -c, --bytes=SIZE         print first SIZE bytes\n\
  399.   -l, -n, --lines=NUMBER   print first NUMBER lines instead of first 10\n\
  400.   -q, --quiet, --silent    never print headers giving file names\n\
  401.   -v, --verbose            always print headers giving file names\n\
  402.       --help               display this help and exit\n\
  403.       --version            output version information and exit\n\
  404. \n\
  405. SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
  406. If -VALUE is used as first OPTION, read -c VALUE when one of\n\
  407. multipliers bkm follows concatenated, else read -n VALUE.  With no\n\
  408. FILE, or when FILE is -, read standard input.\n\
  409. ");
  410.     }
  411.   exit (status);
  412. }
  413.