From 9c84e900391f604d38f083315d433fc86a9e58c5 Mon Sep 17 00:00:00 2001 From: Gitea Date: Sun, 13 Dec 2020 09:37:32 -0600 Subject: [PATCH] Moved to getopt() --- cmp.c | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) 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);