Oops. Forgot these....
[oweals/busybox.git] / coreutils / cmp.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini cmp implementation for busybox
4  *
5  * Copyright (C) 2000,2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
6  *
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.
11  *
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.
16  *
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 02111-1307 USA
20  *
21  */
22
23 #include <stdio.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <getopt.h>
28 #include "busybox.h"
29
30 int cmp_main(int argc, char **argv)
31 {
32         FILE *fp1 = NULL, *fp2 = stdin;
33         char *filename1, *filename2 = "-";
34         int c, c1, c2, char_pos = 1, line_pos = 1, silent = FALSE;
35
36         while ((c = getopt(argc, argv, "s")) != EOF) {
37                 switch (c) {
38                         case 's':
39                                 silent = TRUE;
40                                 break;
41                         default:
42                                 show_usage();
43                 }
44         }
45
46         filename1 = argv[optind];
47         switch (argc - optind) {
48                 case 2:
49                         fp2 = xfopen(filename2 = argv[optind + 1], "r");
50                 case 1:
51                         fp1 = xfopen(filename1, "r");
52                         break;
53                 default:
54                         show_usage();
55         }
56
57         do {
58                 c1 = fgetc(fp1);
59                 c2 = fgetc(fp2);
60                 if (c1 != c2) {
61                         if (silent)
62                                 return EXIT_FAILURE;
63                         if (c1 == EOF)
64                                 printf("EOF on %s\n", filename1);
65                         else if (c2 == EOF)
66                                 printf("EOF on %s\n", filename2);
67                         else
68                                 printf("%s %s differ: char %d, line %d\n", filename1, filename2,
69                                                 char_pos, line_pos);
70                         return EXIT_FAILURE;
71                 }
72                 char_pos++;
73                 if (c1 == '\n')
74                         line_pos++;
75         } while (c1 != EOF);
76
77         return EXIT_SUCCESS;
78 }