diff --git a/coreutils/cmp.c b/coreutils/cmp.c index f47e93b..3e3e680 100644 --- a/coreutils/cmp.c +++ b/coreutils/cmp.c @@ -1,6 +1,7 @@ #include #include #include +#include #include unsigned int s_flag; @@ -53,45 +54,48 @@ FILE *file_open(const char *path) { return fp; } -int main(const int argc, const char **argv) { - int i; - for (i = 1; i < argc; i++) { - if (argv[i][0] != '-') - break; +int main(int argc, char **argv) { + int opt; + while ((opt = getopt(argc, argv, "f")) != -1) { + switch (opt) { + case 'f': + s_flag = 1; + break; - else if (!strcmp(argv[i], "-n")) - s_flag = 1; - - else if (!strcmp(argv[i], "--help")) { - printf("cmp FILE1 FILE2 [SKIP1] [SKIP2]\n\t[-f Silent]\n"); - return 0; + default: + printf("cmp file1 file2 [skip1] [skip2]\n\t[-f Silent]\n"); + return 0; } } + argv += optind; + argc -= optind; + long skip1 = 0; long skip2 = 0; FILE *fp1 = NULL; FILE *fp2 = stdin; - switch (argc - i) { + switch (argc) { case 4: - skip2 = parse_int(argv[i + 3]); + skip2 = parse_int(argv[3]); /* fallthrough */ case 3: - skip1 = parse_int(argv[i + 2]); + skip1 = parse_int(argv[2]); /* fallthrough */ case 2: - fp2 = file_open(argv[i + 1]); + fp2 = file_open(argv[1]); /* fallthrough */ case 1: - fp1 = file_open(argv[i]); + fp1 = file_open(argv[0]); break; default: + fprintf(stderr, "cmp: missing operand\n"); return 1; }