/* file11 has the same effect as file10, but simplifies main() by using the auxiliary functions safefopen() and safereadbyte(). */ #include #include #include void die(char *operation,char *filename) { fprintf(stderr,"fatal: unable to %s %s: %s\n" ,operation,filename,strerror(errno)); exit(111); } void exit_same(void) { printf("The files have the same contents.\n"); exit(0); } void exit_different(void) { printf("The files have different contents.\n"); exit(0); } FILE *safefopen(char *filename,char *how) { FILE *f = fopen(filename,how); if (!f) die("open",filename); return f; } int safereadbyte(char *filename,FILE *f,char *result) { if (fscanf(f,"%c",result) == 1) return 1; if (ferror(f)) die("read",filename); return 0; } int main(int argc,char **argv) { FILE *f1; FILE *f2; char c1; char c2; if (argc < 3) { fprintf(stderr,"usage: file11 f1 f2\n"); exit(100); } f1 = safefopen(argv[1],"r"); f2 = safefopen(argv[2],"r"); for (;;) if (!safereadbyte(argv[1],f1,&c1)) if (!safereadbyte(argv[2],f2,&c2)) exit_same(); else exit_different(); else if (!safereadbyte(argv[2],f2,&c2)) exit_different(); else if (c1 != c2) exit_different(); }