736a60d82b551ef81b2228e91b226e2a31e07483
[platform/upstream/coreutils.git] / src / comm.c
1 /* comm -- compare two sorted files line by line.
2    Copyright (C) 86, 90, 91, 1995-2003 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 Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Richard Stallman and David MacKenzie. */
19 \f
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <getopt.h>
24 #include <sys/types.h>
25 #include "system.h"
26 #include "linebuffer.h"
27 #include "error.h"
28 #include "hard-locale.h"
29 #include "xmemcoll.h"
30
31 /* The official name of this program (e.g., no `g' prefix).  */
32 #define PROGRAM_NAME "comm"
33
34 #define WRITTEN_BY _("Written by Richard Stallman and David MacKenzie.")
35
36 /* Undefine, to avoid warning about redefinition on some systems.  */
37 #undef min
38 #define min(x, y) ((x) < (y) ? (x) : (y))
39
40 /* The name this program was run with. */
41 char *program_name;
42
43 /* Nonzero if the LC_COLLATE locale is hard.  */
44 static int hard_LC_COLLATE;
45
46 /* If nonzero, print lines that are found only in file 1. */
47 static int only_file_1;
48
49 /* If nonzero, print lines that are found only in file 2. */
50 static int only_file_2;
51
52 /* If nonzero, print lines that are found in both files. */
53 static int both;
54
55 static struct option const long_options[] =
56 {
57   {GETOPT_HELP_OPTION_DECL},
58   {GETOPT_VERSION_OPTION_DECL},
59   {0, 0, 0, 0}
60 };
61
62 \f
63
64 void
65 usage (int status)
66 {
67   if (status != 0)
68     fprintf (stderr, _("Try `%s --help' for more information.\n"),
69              program_name);
70   else
71     {
72       printf (_("\
73 Usage: %s [OPTION]... LEFT_FILE RIGHT_FILE\n\
74 "),
75               program_name);
76       fputs (_("\
77 Compare sorted files LEFT_FILE and RIGHT_FILE line by line.\n\
78 \n\
79   -1              suppress lines unique to left file\n\
80   -2              suppress lines unique to right file\n\
81   -3              suppress lines that appear in both files\n\
82 "), stdout);
83       fputs (HELP_OPTION_DESCRIPTION, stdout);
84       fputs (VERSION_OPTION_DESCRIPTION, stdout);
85       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
86     }
87   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
88 }
89
90 /* Output the line in linebuffer LINE to stream STREAM
91    provided the switches say it should be output.
92    CLASS is 1 for a line found only in file 1,
93    2 for a line only in file 2, 3 for a line in both. */
94
95 static void
96 writeline (const struct linebuffer *line, FILE *stream, int class)
97 {
98   switch (class)
99     {
100     case 1:
101       if (!only_file_1)
102         return;
103       break;
104
105     case 2:
106       if (!only_file_2)
107         return;
108       /* Print a TAB if we are printing lines from file 1.  */
109       if (only_file_1)
110         putc ('\t', stream);
111       break;
112
113     case 3:
114       if (!both)
115         return;
116       /* Print a TAB if we are printing lines from file 1.  */
117       if (only_file_1)
118         putc ('\t', stream);
119       /* Print a TAB if we are printing lines from file 2.  */
120       if (only_file_2)
121         putc ('\t', stream);
122       break;
123     }
124
125   fwrite (line->buffer, sizeof (char), line->length, stream);
126 }
127
128 /* Compare INFILES[0] and INFILES[1].
129    If either is "-", use the standard input for that file.
130    Assume that each input file is sorted;
131    merge them and output the result.
132    Return 0 if successful, 1 if any errors occur. */
133
134 static int
135 compare_files (char **infiles)
136 {
137   /* For each file, we have one linebuffer in lb1.  */
138   struct linebuffer lb1[2];
139
140   /* thisline[i] points to the linebuffer holding the next available line
141      in file i, or is NULL if there are no lines left in that file.  */
142   struct linebuffer *thisline[2];
143
144   /* streams[i] holds the input stream for file i.  */
145   FILE *streams[2];
146
147   /* errno values for each stream.  */
148   int saved_errno[2];
149
150   int i, ret = 0;
151
152   /* Initialize the storage. */
153   for (i = 0; i < 2; i++)
154     {
155       initbuffer (&lb1[i]);
156       thisline[i] = &lb1[i];
157       streams[i] = (STREQ (infiles[i], "-") ? stdin : fopen (infiles[i], "r"));
158       if (!streams[i])
159         {
160           error (0, errno, "%s", infiles[i]);
161           return 1;
162         }
163
164       thisline[i] = readlinebuffer (thisline[i], streams[i]);
165       saved_errno[i] = errno;
166     }
167
168   while (thisline[0] || thisline[1])
169     {
170       int order;
171
172       /* Compare the next available lines of the two files.  */
173
174       if (!thisline[0])
175         order = 1;
176       else if (!thisline[1])
177         order = -1;
178       else
179         {
180           if (HAVE_SETLOCALE && hard_LC_COLLATE)
181             order = xmemcoll (thisline[0]->buffer, thisline[0]->length - 1,
182                               thisline[1]->buffer, thisline[1]->length - 1);
183           else
184             {
185               size_t len = min (thisline[0]->length, thisline[1]->length) - 1;
186               order = memcmp (thisline[0]->buffer, thisline[1]->buffer, len);
187               if (order == 0)
188                 order = (thisline[0]->length < thisline[1]->length
189                          ? -1
190                          : thisline[0]->length != thisline[1]->length);
191             }
192         }
193
194       /* Output the line that is lesser. */
195       if (order == 0)
196         writeline (thisline[1], stdout, 3);
197       else if (order > 0)
198         writeline (thisline[1], stdout, 2);
199       else
200         writeline (thisline[0], stdout, 1);
201
202       /* Step the file the line came from.
203          If the files match, step both files.  */
204       if (order >= 0)
205         {
206           thisline[1] = readlinebuffer (thisline[1], streams[1]);
207           saved_errno[1] = errno;
208         }
209       if (order <= 0)
210         {
211           thisline[0] = readlinebuffer (thisline[0], streams[0]);
212           saved_errno[0] = errno;
213         }
214     }
215
216   /* Free all storage and close all input streams. */
217   for (i = 0; i < 2; i++)
218     {
219       free (lb1[i].buffer);
220       if (ferror (streams[i]))
221         {
222           error (0, saved_errno[i], "%s", infiles[i]);
223           ret = 1;
224         }
225       if (fclose (streams[i]) != 0)
226         {
227           error (0, errno, "%s", infiles[i]);
228           ret = 1;
229         }
230     }
231   return ret;
232 }
233
234 int
235 main (int argc, char **argv)
236 {
237   int c;
238
239   initialize_main (&argc, &argv);
240   program_name = argv[0];
241   setlocale (LC_ALL, "");
242   bindtextdomain (PACKAGE, LOCALEDIR);
243   textdomain (PACKAGE);
244   hard_LC_COLLATE = hard_locale (LC_COLLATE);
245
246   atexit (close_stdout);
247
248   only_file_1 = 1;
249   only_file_2 = 1;
250   both = 1;
251
252   while ((c = getopt_long (argc, argv, "123", long_options, NULL)) != -1)
253     switch (c)
254       {
255       case 0:
256         break;
257
258       case '1':
259         only_file_1 = 0;
260         break;
261
262       case '2':
263         only_file_2 = 0;
264         break;
265
266       case '3':
267         both = 0;
268         break;
269
270       case_GETOPT_HELP_CHAR;
271
272       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
273
274       default:
275         usage (EXIT_FAILURE);
276       }
277
278   if (optind + 2 != argc)
279     {
280       error (0, 0, _("too few arguments"));
281       usage (EXIT_FAILURE);
282     }
283
284   exit (compare_files (argv + optind) == 0
285         ? EXIT_SUCCESS : EXIT_FAILURE);
286 }