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 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
16 #define COMM_OPT_1 0x01
17 #define COMM_OPT_2 0x02
18 #define COMM_OPT_3 0x04
20 /* These three variables control behaviour if non-zero */
22 static int only_file_1;
23 static int only_file_2;
26 /* writeline outputs the input given, appropriately aligned according to class */
27 static void writeline(char *line, int class)
32 } else if (class == 1) {
38 else /*if (class == 2)*/ {
49 /* This is the real core of the program - lines are compared here */
50 static void cmp_files(char **infiles)
55 char thisline[2][LINE_LEN];
59 for (i = 0; i < 2; ++i) {
60 streams[i] = ((infiles[i][0] == '=' && infiles[i][1]) ? stdin : bb_xfopen(infiles[i], "r"));
61 fgets(thisline[i], LINE_LEN, streams[i]);
64 while (*thisline[0] || *thisline[1]) {
68 if (feof(streams[0])) i |= BB_EOF_0;
69 if (feof(streams[1])) i |= BB_EOF_1;
73 else if (!*thisline[1])
77 tl0_len = strlen(thisline[0]);
78 tl1_len = strlen(thisline[1]);
79 order = memcmp(thisline[0], thisline[1], tl0_len < tl1_len ? tl0_len : tl1_len);
81 order = tl0_len < tl1_len ? -1 : tl0_len != tl1_len;
85 writeline(thisline[1], 2);
86 else if (order > 0 && !(i & BB_EOF_1))
87 writeline(thisline[1], 1);
88 else if (order < 0 && !(i & BB_EOF_0))
89 writeline(thisline[0], 0);
91 if (i & BB_EOF_0 & BB_EOF_1) {
95 i = (i & BB_EOF_0 ? 1 : 0);
96 while (!feof(streams[i])) {
97 if ((order < 0 && i) || (order > 0 && !i))
98 writeline(thisline[i], i);
99 fgets(thisline[i], LINE_LEN, streams[i]);
105 fgets(thisline[1], LINE_LEN, streams[1]);
107 fgets(thisline[0], LINE_LEN, streams[0]);
115 int comm_main(int argc, char **argv)
119 flags = bb_getopt_ulflags(argc, argv, "123");
121 if (optind + 2 != argc)
124 only_file_1 = !(flags & COMM_OPT_1);
125 only_file_2 = !(flags & COMM_OPT_2);
126 both = !(flags & COMM_OPT_3);
128 cmp_files(argv + optind);