home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / rcs57pc3.zip / diff / cmp.c < prev    next >
C/C++ Source or Header  |  1999-03-29  |  15KB  |  589 lines

  1. /* cmp -- compare two files.
  2.    Copyright (C) 1990, 1991, 1992, 1993, 1994 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. /* Written by Torbjorn Granlund and David MacKenzie. */
  19.  
  20. #include "system.h"
  21. #include <stdio.h>
  22. #include "getopt.h"
  23. #include "cmpbuf.h"
  24.  
  25. extern char const version_string[];
  26.  
  27. #if __STDC__ && defined (HAVE_VPRINTF)
  28. void error (int, int, char const *, ...);
  29. #else
  30. void error ();
  31. #endif
  32. VOID *xmalloc PARAMS((size_t));
  33. extern int xmalloc_exit_failure;
  34.  
  35. static int cmp PARAMS((void));
  36. static off_t file_position PARAMS((int));
  37. static size_t block_compare PARAMS((char const *, char const *));
  38. static size_t block_compare_and_count PARAMS((char const *, char const *, long *));
  39. static size_t block_read PARAMS((int, char *, size_t));
  40. static void sprintc PARAMS((char *, int, unsigned));
  41. static void try_help PARAMS((char const *));
  42. static void check_stdout PARAMS((void));
  43. static void usage PARAMS((void));
  44.  
  45. /* Name under which this program was invoked.  */
  46. char *program_name;
  47.  
  48. /* Filenames of the compared files.  */
  49. static char const *file[2];
  50.  
  51. /* File descriptors of the files.  */
  52. static int file_desc[2];
  53.  
  54. /* Read buffers for the files.  */
  55. static char *buffer[2];
  56.  
  57. /* Optimal block size for the files.  */
  58. static size_t buf_size;
  59.  
  60. /* Initial prefix to ignore for each file.  */
  61. static off_t ignore_initial;
  62.  
  63. /* Output format:
  64.    type_first_diff
  65.      to print the offset and line number of the first differing bytes
  66.    type_all_diffs
  67.      to print the (decimal) offsets and (octal) values of all differing bytes
  68.    type_status
  69.      to only return an exit status indicating whether the files differ */
  70. static enum
  71.   {
  72.     type_first_diff, type_all_diffs, type_status
  73.   } comparison_type;
  74.  
  75. /* Type used for fast comparison of several bytes at a time.  */
  76. #ifndef word
  77. #define word int
  78. #endif
  79.  
  80. /* If nonzero, print values of bytes quoted like cat -t does. */
  81. static int opt_print_chars;
  82.  
  83. static struct option const long_options[] =
  84. {
  85.   {"print-chars", 0, 0, 'c'},
  86.   {"ignore-initial", 1, 0, 'i'},
  87.   {"verbose", 0, 0, 'l'},
  88.   {"silent", 0, 0, 's'},
  89.   {"quiet", 0, 0, 's'},
  90.   {"version", 0, 0, 'v'},
  91.   {"help", 0, 0, 129},
  92.   {0, 0, 0, 0}
  93. };
  94.  
  95. static void
  96. try_help (reason_msgid)
  97.      char const *reason_msgid;
  98. {
  99.   if (reason_msgid)
  100.     error (0, 0, "%s", gettext (reason_msgid));
  101.   error (2, 0, gettext ("Try `%s --help' for more information."), program_name);
  102. }
  103.  
  104. static void
  105. check_stdout ()
  106. {
  107.   if (ferror (stdout))
  108.     error (2, 0, gettext ("write failed"));
  109.   else if (fclose (stdout) != 0)
  110.     error (2, errno, gettext ("write failed"));
  111. }
  112.  
  113. static char const * const option_help_msgid[] = {
  114.   "-c  --print-chars  Output differing bytes as characters.",
  115.   "-i N  --ignore-initial=N  Ignore differences in the first N bytes of input.",
  116.   "-l  --verbose  Output offsets and codes of all differing bytes.",
  117.   "-s  --quiet  --silent  Output nothing; yield exit status only.",
  118.   "-v  --version  Output version info.",
  119.   "--help  Output this help.",
  120.   0
  121. };
  122.  
  123. static void
  124. usage ()
  125. {
  126.   char const * const *p;
  127.  
  128.   printf (gettext ("Usage: %s [OPTION]... FILE1 [FILE2]\n"), program_name);
  129.   for (p = option_help_msgid;  *p;  p++)
  130.     printf ("  %s\n", gettext (*p));
  131.   printf (gettext ("If a FILE is `-' or missing, read standard input.\n"));
  132. }
  133.  
  134. int
  135. main (argc, argv)
  136.      int argc;
  137.      char *argv[];
  138. {
  139.   int c, i, exit_status;
  140.   struct stat stat_buf[2];
  141.   size_t alloc_size;
  142.  
  143.   initialize_main (&argc, &argv);
  144.   setlocale (LC_ALL, "");
  145.   program_name = argv[0];
  146.   xmalloc_exit_failure = 2;
  147.  
  148.   /* Parse command line options.  */
  149.  
  150.   while ((c = getopt_long (argc, argv, "ci:lsv", long_options, 0))
  151.      != EOF)
  152.     switch (c)
  153.       {
  154.       case 'c':
  155.     opt_print_chars = 1;
  156.     break;
  157.  
  158.       case 'i':
  159.     ignore_initial = 0;
  160.     while (*optarg)
  161.       {
  162.         /* Don't use `atol', because `off_t' may be longer than `long'.  */
  163.         unsigned digit = *optarg++ - '0';
  164.         if (9 < digit)
  165.           try_help ("--ignore-initial value must be a nonnegative integer");
  166.         ignore_initial = 10 * ignore_initial + digit;
  167.       }
  168.     break;
  169.  
  170.       case 'l':
  171.     comparison_type = type_all_diffs;
  172.     break;
  173.  
  174.       case 's':
  175.     comparison_type = type_status;
  176.     break;
  177.  
  178.       case 'v':
  179.     printf ("cmp - %s\n", version_string);
  180.     exit (0);
  181.  
  182.       case 129:
  183.     usage ();
  184.     check_stdout ();
  185.     exit (0);
  186.  
  187.       default:
  188.     try_help (0);
  189.       }
  190.  
  191.   if (optind == argc)
  192.     try_help ("missing operand");
  193.  
  194.   file[0] = argv[optind++];
  195.   file[1] = optind < argc ? argv[optind++] : "-";
  196.  
  197.   if (optind < argc)
  198.     try_help ("extra operand");
  199.  
  200.   for (i = 0; i < 2; i++)
  201.     {
  202.       /* If file[1] is "-", treat it first; this avoids a misdiagnostic if
  203.      stdin is closed and opening file[0] yields file descriptor 0.  */
  204.       int i1 = i ^ (strcmp (file[1], "-") == 0);
  205.  
  206.       /* Two files with the same name are identical.
  207.      But wait until we open the file once, for proper diagnostics.  */
  208.       if (i && filename_cmp (file[0], file[1]) == 0)
  209.     exit (0);
  210.  
  211.       file_desc[i1] = (strcmp (file[i1], "-") == 0
  212.                ? STDIN_FILENO
  213.                : open (file[i1], O_RDONLY, 0));
  214.       if (file_desc[i1] < 0 || fstat (file_desc[i1], &stat_buf[i1]) != 0)
  215.     {
  216.       if (file_desc[i1] < 0 && comparison_type == type_status)
  217.         exit (2);
  218.       else
  219.         error (2, errno, "%s", file[i1]);
  220.     }
  221. #if HAVE_SETMODE
  222.       setmode (file_desc[i1], O_BINARY);
  223. #endif
  224.     }
  225.  
  226.   /* If the files are links to the same inode and have the same file position,
  227.      they are identical.  */
  228.  
  229.   if (0 < same_file (&stat_buf[0], &stat_buf[1])
  230.       && file_position (0) == file_position (1))
  231.     exit (0);
  232.  
  233.   /* If output is redirected to the null device, we may assume `-s'.  */
  234.  
  235.   if (comparison_type != type_status)
  236.     {
  237.       struct stat outstat, nullstat;
  238.  
  239.       if (fstat (STDOUT_FILENO, &outstat) == 0
  240.       && stat (NULL_DEVICE, &nullstat) == 0
  241.       && 0 < same_file (&outstat, &nullstat))
  242.     comparison_type = type_status;
  243.     }
  244.  
  245.   /* If only a return code is needed,
  246.      and if both input descriptors are associated with plain files,
  247.      conclude that the files differ if they have different sizes.  */
  248.  
  249.   if (comparison_type == type_status
  250.       && S_ISREG (stat_buf[0].st_mode)
  251.       && S_ISREG (stat_buf[1].st_mode))
  252.     {
  253.       off_t s0 = stat_buf[0].st_size - file_position (0);
  254.       off_t s1 = stat_buf[1].st_size - file_position (1);
  255.  
  256.       if (max (0, s0) != max (0, s1))
  257.     exit (1);
  258.     }
  259.  
  260.   /* Get the optimal block size of the files.  */
  261.  
  262.   buf_size = buffer_lcm (STAT_BLOCKSIZE (stat_buf[0]),
  263.              STAT_BLOCKSIZE (stat_buf[1]));
  264.  
  265.   /* Allocate word-aligned buffers, with space for sentinels at the end.  */
  266.  
  267.   alloc_size = buf_size + 2 * sizeof (word) - 1;
  268.   alloc_size -= alloc_size % sizeof (word);
  269.   buffer[0] = xmalloc (2 * alloc_size);
  270.   buffer[1] = buffer[0] + alloc_size;
  271.  
  272.   exit_status = cmp ();
  273.  
  274.   for (i = 0; i < 2; i++)
  275.     if (close (file_desc[i]) != 0)
  276.       error (2, errno, "%s", file[i]);
  277.   if (exit_status != 0  &&  comparison_type != type_status)
  278.     check_stdout ();
  279.   exit (exit_status);
  280.   return exit_status;
  281. }
  282.  
  283. /* Compare the two files already open on `file_desc[0]' and `file_desc[1]',
  284.    using `buffer[0]' and `buffer[1]'.
  285.    Return 0 if identical, 1 if different, >1 if error. */
  286.  
  287. static int
  288. cmp ()
  289. {
  290.   long line_number = 1;        /* Line number (1...) of first difference. */
  291.   long char_number = ignore_initial + 1;
  292.                 /* Offset (1...) in files of 1st difference. */
  293.   size_t read0, read1;        /* Number of chars read from each file. */
  294.   size_t first_diff;        /* Offset (0...) in buffers of 1st diff. */
  295.   size_t smaller;        /* The lesser of `read0' and `read1'. */
  296.   char *buf0 = buffer[0];
  297.   char *buf1 = buffer[1];
  298.   int ret = 0;
  299.   int i;
  300.  
  301.   if (ignore_initial)
  302.     for (i = 0; i < 2; i++)
  303.       if (file_position (i) == -1)
  304.     {
  305.       /* lseek failed; read and discard the ignored initial prefix.  */
  306.       off_t ig = ignore_initial;
  307.       do
  308.         {
  309.           size_t r = read (file_desc[i], buf0, (size_t) min (ig, buf_size));
  310.           if (!r)
  311.         break;
  312.           if (r == -1)
  313.         error (2, errno, "%s", file[i]);
  314.           ig -= r;
  315.         }
  316.       while (ig);
  317.     }
  318.  
  319.   do
  320.     {
  321.       read0 = block_read (file_desc[0], buf0, buf_size);
  322.       if (read0 == -1)
  323.     error (2, errno, "%s", file[0]);
  324.       read1 = block_read (file_desc[1], buf1, buf_size);
  325.       if (read1 == -1)
  326.     error (2, errno, "%s", file[1]);
  327.  
  328.       /* Insert sentinels for the block compare.  */
  329.  
  330.       buf0[read0] = ~buf1[read0];
  331.       buf1[read1] = ~buf0[read1];
  332.  
  333.       /* If the line number should be written for differing files,
  334.      compare the blocks and count the number of newlines
  335.      simultaneously.  */
  336.       first_diff = (comparison_type == type_first_diff
  337.             ? block_compare_and_count (buf0, buf1, &line_number)
  338.             : block_compare (buf0, buf1));
  339.  
  340.       char_number += first_diff;
  341.       smaller = min (read0, read1);
  342.  
  343.       if (first_diff < smaller)
  344.     {
  345.       switch (comparison_type)
  346.         {
  347.         case type_first_diff:
  348.           if (!opt_print_chars)
  349.         {
  350.           /* See Posix.2 section 4.10.6.1 for this format.  */
  351.           printf (gettext ("%s %s differ: char %lu, line %lu\n"),
  352.               file[0], file[1], char_number, line_number);
  353.         }
  354.           else
  355.         {
  356.           unsigned char c0 = buf0[first_diff];
  357.           unsigned char c1 = buf1[first_diff];
  358.           char s0[5];
  359.           char s1[5];
  360.           sprintc (s0, 0, c0);
  361.           sprintc (s1, 0, c1);
  362.           printf (gettext ("%s %s differ: char %lu, line %lu is %3o %s %3o %s\n"),
  363.               file[0], file[1], char_number, line_number,
  364.               c0, s0, c1, s1);
  365.         }
  366.           /* Fall through.  */
  367.         case type_status:
  368.           return 1;
  369.  
  370.         case type_all_diffs:
  371.           do
  372.         {
  373.           unsigned char c0 = buf0[first_diff];
  374.           unsigned char c1 = buf1[first_diff];
  375.           if (c0 != c1)
  376.             {
  377.               if (opt_print_chars)
  378.             {
  379.               char s0[5];
  380.               char s1[5];
  381.               sprintc (s0, 4, c0);
  382.               sprintc (s1, 0, c1);
  383.               printf ("%6lu %3o %s %3o %s\n",
  384.                   char_number, c0, s0, c1, s1);
  385.             }
  386.               else
  387.             /* See Posix.2 section 4.10.6.1 for this format.  */
  388.             printf ("%6lu %3o %3o\n", char_number, c0, c1);
  389.             }
  390.           char_number++;
  391.           first_diff++;
  392.         }
  393.           while (first_diff < smaller);
  394.           ret = 1;
  395.           break;
  396.         }
  397.     }
  398.  
  399.       if (read0 != read1)
  400.     {
  401.       if (comparison_type != type_status)
  402.         /* See Posix.2 section 4.10.6.2 for this format.  */
  403.         fprintf (stderr, gettext ("cmp: EOF on %s\n"),
  404.              file[read1 < read0]);
  405.  
  406.       return 1;
  407.     }
  408.     }
  409.   while (read0 == buf_size);
  410.   return ret;
  411. }
  412.  
  413. /* Compare two blocks of memory P0 and P1 until they differ,
  414.    and count the number of '\n' occurrences in the common
  415.    part of P0 and P1.
  416.    Assumes that P0 and P1 are aligned at word addresses!
  417.    If the blocks are not guaranteed to be different, put sentinels at the ends
  418.    of the blocks before calling this function.
  419.  
  420.    Return the offset of the first byte that differs.
  421.    Increment *COUNT by the count of '\n' occurrences.  */
  422.  
  423. static size_t
  424. block_compare_and_count (p0, p1, count)
  425.      char const *p0, *p1;
  426.      long *count;
  427. {
  428.   word l;        /* One word from first buffer. */
  429.   word const *l0, *l1;    /* Pointers into each buffer. */
  430.   char const *c0, *c1;    /* Pointers for finding exact address. */
  431.   long cnt = 0;        /* Number of '\n' occurrences. */
  432.   word nnnn;        /* Newline, sizeof (word) times.  */
  433.   int i;
  434.  
  435.   l0 = (word const *) p0;
  436.   l1 = (word const *) p1;
  437.  
  438.   nnnn = 0;
  439.   for (i = 0; i < sizeof (word); i++)
  440.     nnnn = (nnnn << CHAR_BIT) | '\n';
  441.  
  442.   /* Find the rough position of the first difference by reading words,
  443.      not bytes.  */
  444.  
  445.   while ((l = *l0++) == *l1++)
  446.     {
  447.       l ^= nnnn;
  448.       for (i = 0; i < sizeof (word); i++)
  449.     {
  450.       cnt += ! (unsigned char) l;
  451.       l >>= CHAR_BIT;
  452.     }
  453.     }
  454.  
  455.   /* Find the exact differing position (endianness independent).  */
  456.  
  457.   c0 = (char const *) (l0 - 1);
  458.   c1 = (char const *) (l1 - 1);
  459.   while (*c0 == *c1)
  460.     {
  461.       cnt += *c0 == '\n';
  462.       c0++;
  463.       c1++;
  464.     }
  465.  
  466.   *count += cnt;
  467.   return c0 - p0;
  468. }
  469.  
  470. /* Compare two blocks of memory P0 and P1 until they differ.
  471.    Assumes that P0 and P1 are aligned at word addresses!
  472.    If the blocks are not guaranteed to be different, put sentinels at the ends
  473.    of the blocks before calling this function.
  474.  
  475.    Return the offset of the first byte that differs.  */
  476.  
  477. static size_t
  478. block_compare (p0, p1)
  479.      char const *p0, *p1;
  480. {
  481.   word const *l0, *l1;
  482.   char const *c0, *c1;
  483.  
  484.   l0 = (word const *) p0;
  485.   l1 = (word const *) p1;
  486.  
  487.   /* Find the rough position of the first difference by reading words,
  488.      not bytes.  */
  489.  
  490.   while (*l0++ == *l1++)
  491.     ;
  492.  
  493.   /* Find the exact differing position (endianness independent).  */
  494.  
  495.   c0 = (char const *) (l0 - 1);
  496.   c1 = (char const *) (l1 - 1);
  497.   while (*c0 == *c1)
  498.     {
  499.       c0++;
  500.       c1++;
  501.     }
  502.  
  503.   return c0 - p0;
  504. }
  505.  
  506. /* Read NCHARS bytes from descriptor FD into BUF.
  507.    Return the number of characters successfully read.
  508.    The number returned is always NCHARS unless end-of-file or error.  */
  509.  
  510. static size_t
  511. block_read (fd, buf, nchars)
  512.      int fd;
  513.      char *buf;
  514.      size_t nchars;
  515. {
  516.   char *bp = buf;
  517.  
  518.   do
  519.     {
  520.       size_t nread = read (fd, bp, nchars);
  521.       if (nread == -1)
  522.     return -1;
  523.       if (nread == 0)
  524.     break;
  525.       bp += nread;
  526.       nchars -= nread;
  527.     }
  528.   while (nchars != 0);
  529.  
  530.   return bp - buf;
  531. }
  532.  
  533. /* Put into BUF the character C, making unprintable characters
  534.    visible by quoting like cat -t does.
  535.    Pad with spaces on the right to WIDTH characters.  */
  536.  
  537. static void
  538. sprintc (buf, width, c)
  539.      char *buf;
  540.      int width;
  541.      unsigned c;
  542. {
  543.   if (! ISPRINT (c))
  544.     {
  545.       if (c >= 128)
  546.     {
  547.       *buf++ = 'M';
  548.       *buf++ = '-';
  549.       c -= 128;
  550.       width -= 2;
  551.     }
  552.       if (c < 32)
  553.     {
  554.       *buf++ = '^';
  555.       c += 64;
  556.       --width;
  557.     }
  558.       else if (c == 127)
  559.     {
  560.       *buf++ = '^';
  561.       c = '?';
  562.       --width;
  563.     }
  564.     }
  565.  
  566.   *buf++ = c;
  567.   while (--width > 0)
  568.     *buf++ = ' ';
  569.   *buf = 0;
  570. }
  571.  
  572. /* Position file I to `ignore_initial' bytes from its initial position,
  573.    and yield its new position.  Don't try more than once.  */
  574.  
  575. static off_t
  576. file_position (i)
  577.      int i;
  578. {
  579.   static int positioned[2];
  580.   static off_t position[2];
  581.  
  582.   if (! positioned[i])
  583.     {
  584.       positioned[i] = 1;
  585.       position[i] = lseek (file_desc[i], ignore_initial, SEEK_CUR);
  586.     }
  587.   return position[i];
  588. }
  589.