home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / rcs567s.zip / diff / cmp.c < prev    next >
C/C++ Source or Header  |  1993-11-14  |  14KB  |  553 lines

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