1 /* vi: set sw=4 ts=4: */
3 * Mini comm implementation for busybox
5 * Copyright (C) 2005 by Robert Sullivan <cogito.ergo.cogito@gmail.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
30 #define COMM_OPT_1 0x01
31 #define COMM_OPT_2 0x02
32 #define COMM_OPT_3 0x04
34 /* These three variables control behaviour if non-zero */
36 static int only_file_1;
37 static int only_file_2;
40 /* writeline outputs the input given, appropriately aligned according to class */
41 static void writeline (char *line, int class)
66 /* This is the real core of the program - lines are compared here */
67 static int cmp_files(char **infiles)
69 char thisline[2][100];
73 for (i = 0; i < 2; i++) {
74 streams[i] = (strcmp(infiles[i], "=") == 0 ? stdin : fopen(infiles[i], "r"));
75 fgets(thisline[i], 100, streams[i]);
78 while (thisline[0] || thisline[1]) {
80 int tl0_len = strlen(thisline[0]);
81 int tl1_len = strlen(thisline[1]);
85 else if (!thisline[1])
88 order = memcmp(thisline[0], thisline[1], tl0_len < tl1_len ? tl0_len : tl1_len);
90 order = tl0_len < tl1_len ? -1 : tl0_len != tl1_len;
93 if ((order == 0) && (!feof(streams[0])) && (!feof(streams[1])))
94 writeline(thisline[1], 3);
95 else if ((order > 0) && (!feof(streams[1])))
96 writeline(thisline[1], 2);
97 else if ((order < 0) && (!feof(streams[0])))
98 writeline(thisline[0], 1);
100 if (feof(streams[0]) && feof(streams[1])) {
105 } else if (feof(streams[0])) {
106 while (!feof(streams[1])) {
108 writeline(thisline[1], 2);
109 fgets(thisline[1], 100, streams[1]);
115 } else if (feof(streams[1])) {
116 while (!feof(streams[0])) {
118 writeline(thisline[0], 1);
119 fgets(thisline[0], 100, streams[0]);
127 fgets(thisline[1], 100, streams[1]);
129 fgets(thisline[0], 100, streams[0]);
136 int comm_main (int argc, char **argv)
143 opt = bb_getopt_ulflags(argc, argv, "123");
145 if (optind != argc + 2)
148 if (opt & COMM_OPT_1)
150 if (opt & COMM_OPT_2)
152 if (opt & COMM_OPT_3)
155 exit(cmp_files(argv + optind) == 0 ? EXIT_SUCCESS : EXIT_FAILURE);