diff --git a/cmp.c b/cmp.c index 56c34c6..92424d8 100755 --- a/cmp.c +++ b/cmp.c @@ -3,6 +3,7 @@ #include #include #include +#include int main(int argc, char ** argv) { int silent_mode = 0; @@ -11,29 +12,25 @@ int main(int argc, char ** argv) { int files_differ = 0; int i, f1num = 1; FILE *file1, *file2; - char c1, c2; + char c1, c2, c; 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++; + while((c = getopt(argc, argv, "sl")) != -1) { + switch(c) { + case 's': silent_mode = 1; print_all_diff = 0; break; + case 'l': print_all_diff = 1; silent_mode = 0; break; } } - 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++; - } + + f1num = optind; + + if(argc - f1num < 2) { + fprintf(stderr, "%s: missing file operand\n", argv[0]); + return 3; } if(strcmp(argv[f1num], "-") == 0 && strcmp(argv[f1num+1], "-") == 0) { - fprintf(stderr, "%s: Cannot accept stdin for both files\n", argv[0]); + fprintf(stderr, "%s: cannot accept stdin for both files\n", argv[0]); return 2; } else if(strcmp(argv[f1num], "-") == 0) { @@ -49,6 +46,16 @@ int main(int argc, char ** argv) { file2 = fopen(argv[f1num+1], "r"); } + if(file1 == NULL) { + fprintf(stderr, "%s: could not open file %s\n", argv[0], argv[f1num]); + return 4; + } + + if(file2 == NULL) { + fprintf(stderr, "%s: could not open file %s\n", argv[0], argv[f1num + 1]); + return 4; + } + if(silent_mode) { c1 = fgetc(file1); c2 = fgetc(file2);