Moved to getopt()

This commit is contained in:
Gitea 2020-12-13 09:37:32 -06:00
parent c09423b0a6
commit 9c84e90039

39
cmp.c
View file

@ -3,6 +3,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h>
int main(int argc, char ** argv) { int main(int argc, char ** argv) {
int silent_mode = 0; int silent_mode = 0;
@ -11,29 +12,25 @@ int main(int argc, char ** argv) {
int files_differ = 0; int files_differ = 0;
int i, f1num = 1; int i, f1num = 1;
FILE *file1, *file2; FILE *file1, *file2;
char c1, c2; char c1, c2, c;
int line = 1, byte = 1; int line = 1, byte = 1;
if(argv[1][0] == '-' && argv[1][1] == 's' && argv[1][2] == '\0') { while((c = getopt(argc, argv, "sl")) != -1) {
silent_mode = 1; switch(c) {
f1num++; case 's': silent_mode = 1; print_all_diff = 0; break;
if(argv[2][0] == '-' && argv[2][1] == 'l' && case 'l': print_all_diff = 1; silent_mode = 0; break;
argv[2][2] == '\0') {
f1num++;
} }
} }
else if(argv[1][0] == '-' && argv[1][1] == 'l' &&
argv[1][2] == '\0') { f1num = optind;
print_all_diff = 1;
f1num++; if(argc - f1num < 2) {
if(argv[2][0] == '-' && argv[2][1] == 's' && fprintf(stderr, "%s: missing file operand\n", argv[0]);
argv[2][2] == '\0') { return 3;
f1num++;
}
} }
if(strcmp(argv[f1num], "-") == 0 && strcmp(argv[f1num+1], "-") == 0) { 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; return 2;
} }
else if(strcmp(argv[f1num], "-") == 0) { else if(strcmp(argv[f1num], "-") == 0) {
@ -49,6 +46,16 @@ int main(int argc, char ** argv) {
file2 = fopen(argv[f1num+1], "r"); 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) { if(silent_mode) {
c1 = fgetc(file1); c1 = fgetc(file1);
c2 = fgetc(file2); c2 = fgetc(file2);