FENIX_coreutils/cmp.c

119 lines
2.5 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv) {
int silent_mode = 0;
int print_all_diff = 0;
int keep_printing = 1;
int files_differ = 0;
int i, f1num = 1;
FILE *file1, *file2;
char c1, c2;
int line = 1, byte = 1;
if(argv[1][0] == '-' && argv[1][1] == 's' && argv[1][2] == '\0') {
silent_mode = 1;
f1num++;
if(argv[2][0] == '-' && argv[2][1] == 'l' &&
argv[2][2] == '\0') {
f1num++;
}
}
else if(argv[1][0] == '-' && argv[1][1] == 'l' &&
argv[1][2] == '\0') {
print_all_diff = 1;
f1num++;
if(argv[2][0] == '-' && argv[2][1] == 's' &&
argv[2][2] == '\0') {
f1num++;
}
}
if(strcmp(argv[f1num], "-") == 0 && strcmp(argv[f1num+1], "-") == 0) {
fprintf(stderr, "%s: Cannot accept stdin for both files\n", argv[0]);
return 2;
}
else if(strcmp(argv[f1num], "-") == 0) {
file1 = stdin;
file2 = fopen(argv[f1num+1], "r");
}
else if(strcmp(argv[f1num+1], "-") == 0) {
file1 = fopen(argv[f1num], "r");
file2 = stdin;
}
else {
file1 = fopen(argv[f1num], "r");
file2 = fopen(argv[f1num+1], "r");
}
if(silent_mode) {
c1 = fgetc(file1);
c2 = fgetc(file2);
for(i = 0; !(c1 == EOF || c2 == EOF); i++) {
if(c1 != c2) {
return 1;
}
c1 = fgetc(file1);
c2 = fgetc(file2);
}
if(c1 != c2) {
return 1;
}
else {
return 0;
}
}
else if(print_all_diff) {
c1 = fgetc(file1);
c2 = fgetc(file2);
for(i = 0; !(c1 == EOF || c2 == EOF); i++) {
if(c1 != c2) {
printf("%d %o %o\n", byte, c1, c2);
files_differ = 1;
}
c1 = fgetc(file1);
c2 = fgetc(file2);
line++;
byte++;
}
if(c1 != c2) {
fprintf(stderr, "%s: EOF on %s%s\n", argv[0],
c1 == EOF ? argv[f1num] : argv[f1num+1], "");
return 1;
}
else if(files_differ) {
return 1;
}
else {
return 0;
}
}
else {
c1 = fgetc(file1);
c2 = fgetc(file2);
for(i = 0; !(c1 == EOF || c2 == EOF); i++) {
if(c1 != c2 && keep_printing) {
keep_printing = 0;
printf("%s %s differ: char %d, line %d\n", argv[f1num], argv[f1num+1], byte, line);
files_differ = 1;
}
c1 = fgetc(file1);
c2 = fgetc(file2);
if(c1 == '\n') line++;
byte++;
}
if(c1 != c2) {
fprintf(stderr, "%s: EOF on %s%s\n", argv[0],
c1 == EOF ? argv[f1num] : argv[f1num+1], "");
return 1;
}
else if(files_differ) {
return 1;
}
else {
return 0;
}
}
}