Mercurial > hg > toybox
comparison toys/posix/cmp.c @ 653:2986aa63a021
Move commands into "posix", "lsb", and "other" menus/directories.
author | Rob Landley <rob@landley.net> |
---|---|
date | Sat, 25 Aug 2012 14:25:22 -0500 |
parents | toys/cmp.c@26098529bbe6 |
children | 6df4ccc0acbe |
comparison
equal
deleted
inserted
replaced
652:2d7c56913fda | 653:2986aa63a021 |
---|---|
1 /* vi: set sw=4 ts=4: | |
2 * | |
3 * cmp.c - Compare two files. | |
4 * | |
5 * Copyright 2012 Timothy Elliott <tle@holymonkey.com> | |
6 * | |
7 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cmp.html | |
8 | |
9 USE_CMP(NEWTOY(cmp, "<2>2ls", TOYFLAG_USR|TOYFLAG_BIN)) | |
10 | |
11 config CMP | |
12 bool "cmp" | |
13 default y | |
14 help | |
15 usage: cmp [-l] [-s] FILE1 FILE2 | |
16 | |
17 Compare the contents of two files. | |
18 | |
19 -l show all differing bytes | |
20 -s silent | |
21 */ | |
22 | |
23 #include "toys.h" | |
24 | |
25 #define FLAG_s 1 | |
26 #define FLAG_l 2 | |
27 | |
28 DEFINE_GLOBALS( | |
29 int fd; | |
30 char *name; | |
31 ) | |
32 | |
33 #define TT this.cmp | |
34 | |
35 // This handles opening the file and | |
36 | |
37 void do_cmp(int fd, char *name) | |
38 { | |
39 int i, len1, len2, min_len, size = sizeof(toybuf)/2; | |
40 long byte_no = 1, line_no = 1; | |
41 char *buf2 = toybuf+size; | |
42 | |
43 // First time through, cache the data and return. | |
44 if (!TT.fd) { | |
45 TT.name = name; | |
46 // On return the old filehandle is closed, and this assures that even | |
47 // if we were called with stdin closed, the new filehandle != 0. | |
48 TT.fd = dup(fd); | |
49 return; | |
50 } | |
51 | |
52 for (;;) { | |
53 len1 = readall(TT.fd, toybuf, size); | |
54 len2 = readall(fd, buf2, size); | |
55 | |
56 min_len = len1 < len2 ? len1 : len2; | |
57 for (i=0; i<min_len; i++) { | |
58 if (toybuf[i] != buf2[i]) { | |
59 toys.exitval = 1; | |
60 if (toys.optflags & FLAG_l) | |
61 printf("%ld %o %o\n", byte_no, toybuf[i], buf2[i]); | |
62 else { | |
63 if (!(toys.optflags & FLAG_s)) { | |
64 printf("%s %s differ: char %ld, line %ld\n", | |
65 TT.name, name, byte_no, line_no); | |
66 toys.exitval++; | |
67 } | |
68 goto out; | |
69 } | |
70 } | |
71 byte_no++; | |
72 if (toybuf[i] == '\n') line_no++; | |
73 } | |
74 if (len1 != len2) { | |
75 if (!(toys.optflags & FLAG_s)) { | |
76 fprintf(stderr, "cmp: EOF on %s\n", | |
77 len1 < len2 ? TT.name : name); | |
78 } | |
79 toys.exitval = 1; | |
80 break; | |
81 } | |
82 if (len1 < 1) break; | |
83 } | |
84 out: | |
85 if (CFG_TOYBOX_FREE) close(TT.fd); | |
86 } | |
87 | |
88 void cmp_main(void) | |
89 { | |
90 loopfiles_rw(toys.optargs, O_RDONLY, 0, toys.optflags&FLAG_s, do_cmp); | |
91 } | |
92 |