/* simple cmp */ #include int main(int argc, char **argv) { FILE *fp1, *fp2; int c, d, i; if (argc != 3) { fprintf(stderr, "usage: cmp file1 file2\n"); return(2); } if ((fp1 = fopen(argv[1], "r")) == NULL) { perror(argv[1]); return(2); } if ((fp2 = fopen(argv[2], "r")) == NULL) { perror(argv[2]); return(2); } /* read until EOF on either file OR a different char in the two files */ for (i = 1; (c = getc(fp1)) != EOF && (d = getc(fp2)) != EOF && c == d; i++) ; /* * At this point we either have * an EOF on file 1; * or no EOF on file 1 but an EOF on file 2; * or no EOF on either file but the chars at this point differ. */ if (c == EOF) { /* eof on file 1; is it also eof on file 2 right now? */ if (getc(fp2) == EOF) return(0); /* simultaneous EOF, thus identical files */ printf("eof on %s\n", argv[1]); return(1); } if (d == EOF) { /* no EOF on file 1, but EOF on file 2 */ printf("eof on %s\n", argv[2]); return(1); } /* no eofs yet the loop exited, thus there is a difference. */ printf("%s %s differ: char %d\n", argv[1], argv[2], i); return(1); }