1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include "libbb.h"
22
23static const char fmt_eof[] ALIGN1 = "cmp: EOF on %s\n";
24static const char fmt_differ[] ALIGN1 = "%s %s differ: char %"OFF_FMT"u, line %u\n";
25
26static const char fmt_l_opt[] ALIGN1 = "%.0s%.0s%"OFF_FMT"u %3o %3o\n";
27
28static const char opt_chars[] ALIGN1 = "sl";
29#define CMP_OPT_s (1<<0)
30#define CMP_OPT_l (1<<1)
31
32int cmp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
33int cmp_main(int argc UNUSED_PARAM, char **argv)
34{
35 FILE *fp1, *fp2, *outfile = stdout;
36 const char *filename1, *filename2 = "-";
37 off_t skip1 = 0, skip2 = 0, char_pos = 0;
38 int line_pos = 1;
39 const char *fmt;
40 int c1, c2;
41 unsigned opt;
42 int retval = 0;
43
44 opt_complementary = "-1"
45 IF_DESKTOP(":?4")
46 IF_NOT_DESKTOP(":?2")
47 ":l--s:s--l";
48 opt = getopt32(argv, opt_chars);
49 argv += optind;
50
51 filename1 = *argv;
52 if (*++argv) {
53 filename2 = *argv;
54 if (ENABLE_DESKTOP && *++argv) {
55 skip1 = XATOOFF(*argv);
56 if (*++argv) {
57 skip2 = XATOOFF(*argv);
58 }
59 }
60 }
61
62 xfunc_error_retval = 2;
63 if (opt & CMP_OPT_s)
64 logmode = 0;
65 fp1 = xfopen_stdin(filename1);
66 fp2 = xfopen_stdin(filename2);
67 if (fp1 == fp2) {
68
69
70
71
72 return 0;
73 }
74 logmode = LOGMODE_STDIO;
75
76 if (opt & CMP_OPT_l)
77 fmt = fmt_l_opt;
78 else
79 fmt = fmt_differ;
80
81 if (ENABLE_DESKTOP) {
82 while (skip1) { getc(fp1); skip1--; }
83 while (skip2) { getc(fp2); skip2--; }
84 }
85 do {
86 c1 = getc(fp1);
87 c2 = getc(fp2);
88 ++char_pos;
89 if (c1 != c2) {
90 retval = 1;
91 if (c2 == EOF) {
92
93
94
95
96 fp1 = fp2;
97 filename1 = filename2;
98 c1 = c2;
99 }
100 if (c1 == EOF) {
101 die_if_ferror(fp1, filename1);
102 fmt = fmt_eof;
103 outfile = stderr;
104
105
106 fflush_all();
107 }
108 if (!(opt & CMP_OPT_s)) {
109 if (opt & CMP_OPT_l) {
110 line_pos = c1;
111 }
112 fprintf(outfile, fmt, filename1, filename2, char_pos, line_pos, c2);
113 if (opt) {
114
115
116 continue;
117 }
118 }
119 break;
120 }
121 if (c1 == '\n') {
122 ++line_pos;
123 }
124 } while (c1 != EOF);
125
126 die_if_ferror(fp1, filename1);
127 die_if_ferror(fp2, filename2);
128
129 fflush_stdout_and_exit(retval);
130}
131