ln: Added ln
[mutos-utils.git] / cmp.c
blob3613218365f3d5e917c292f450c2d7c40bae392d
1 /*
2 Copyright © 2013 Alastair Stuart
4 This program is open source software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
15 #include <stdio.h>
16 #include <string.h>
18 #define VERSION "0.01"
20 int main(int argc, char* argv[])
22 FILE* first_file = NULL;
23 FILE* second_file = NULL;
25 int arg = 0;
26 for (arg = 1; arg < argc; arg++)
28 if (strcmp("--help", argv[arg]) == 0 || strcmp("-h", argv[arg]) == 0) {
29 printf("Usage: %s [file1] [file2]\n", argv[0]);
30 printf("\n"
31 "If a file is '-' or missing, standard input is read.\n");
32 return 0;
33 } else if (strcmp("--version", argv[arg]) == 0 || strcmp("-v", argv[arg]) == 0) {
34 printf("cmp (mutos) v"VERSION"\n");
35 return 0;
36 } else {
37 break;
42 switch (argc - arg) // number of args left
44 case 0:
45 fprintf(stderr, "%s: missing operand\n"
46 "Run '%s --help' for usage.\n",
47 argv[0], argv[0]);
48 return 2;
49 case 1:
50 first_file = strcmp("-", argv[arg]) == 0 ? stdin : fopen(argv[arg], "r");
51 second_file = stdin;
52 break;
53 case 2:
54 first_file = strcmp("-", argv[arg]) == 0 ? stdin : fopen(argv[arg], "r");
55 second_file = strcmp("-", argv[arg+1]) == 0 ? stdin : fopen(argv[arg+1], "r");
56 break;
57 default:
58 fprintf(stderr, "%s: too many arguments\n",
59 argv[0]);
60 return 2;
63 if (first_file == second_file) {
64 return 0;
67 char* first_name = first_file == stdin ? "-" : argv[arg];
68 char* second_name = second_file == stdin ? "-" : argv[arg+1];
70 int differ = 0;
72 int byte_count = 0;
73 int line_count = 1;
75 int first_byte = 0;
76 int second_byte = 0;
79 while (first_byte != EOF && second_byte != EOF)
81 first_byte = fgetc(first_file);
82 second_byte = fgetc(second_file);
83 byte_count++;
85 if (first_byte != second_byte) {
86 differ = 1;
87 break;
90 if (first_byte == '\n') {
91 line_count++;
95 if (differ) {
96 printf("%s %s differ: byte %d, line %d\n",
97 first_name, second_name, byte_count, line_count);
98 fclose(first_file);
99 fclose(second_file);
100 return 1;
101 } else {
102 fclose(first_file);
103 fclose(second_file);
104 return 0;