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.
12 #define COMM_OPT_1 0x01
13 #define COMM_OPT_2 0x02
14 #define COMM_OPT_3 0x04
16 /* These three variables control behaviour if non-zero */
18 static int only_file_1;
19 static int only_file_2;
22 /* writeline outputs the input given, appropriately aligned according to class */
23 static void writeline(char *line, int class)
28 } else if (class == 1) {
34 else /*if (class == 2)*/ {
45 /* This is the real core of the program - lines are compared here */
46 static void cmp_files(char **infiles)
51 char thisline[2][LINE_LEN];
55 for (i = 0; i < 2; ++i) {
56 streams[i] = ((infiles[i][0] == '=' && infiles[i][1]) ? stdin : xfopen(infiles[i], "r"));
57 fgets(thisline[i], LINE_LEN, streams[i]);
60 while (*thisline[0] || *thisline[1]) {
64 if (feof(streams[0])) i |= BB_EOF_0;
65 if (feof(streams[1])) i |= BB_EOF_1;
69 else if (!*thisline[1])
73 tl0_len = strlen(thisline[0]);
74 tl1_len = strlen(thisline[1]);
75 order = memcmp(thisline[0], thisline[1], tl0_len < tl1_len ? tl0_len : tl1_len);
77 order = tl0_len < tl1_len ? -1 : tl0_len != tl1_len;
81 writeline(thisline[1], 2);
82 else if (order > 0 && !(i & BB_EOF_1))
83 writeline(thisline[1], 1);
84 else if (order < 0 && !(i & BB_EOF_0))
85 writeline(thisline[0], 0);
87 if (i & BB_EOF_0 & BB_EOF_1) {
91 i = (i & BB_EOF_0 ? 1 : 0);
92 while (!feof(streams[i])) {
93 if ((order < 0 && i) || (order > 0 && !i))
94 writeline(thisline[i], i);
95 fgets(thisline[i], LINE_LEN, streams[i]);
101 fgets(thisline[1], LINE_LEN, streams[1]);
103 fgets(thisline[0], LINE_LEN, streams[0]);
111 int comm_main(int argc, char **argv)
115 flags = getopt32(argc, argv, "123");
117 if (optind + 2 != argc)
120 only_file_1 = !(flags & COMM_OPT_1);
121 only_file_2 = !(flags & COMM_OPT_2);
122 both = !(flags & COMM_OPT_3);
124 cmp_files(argv + optind);