/* file12 has the same effect as file10 and file11. It eliminates the repeated read-from-f2 in main() by using a variable, havec1, to remember what read-from-f1 returned. */ #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; int havec1; int havec2; if (argc < 3) { fprintf(stderr,"usage: file12 f1 f2\n"); exit(100); } f1 = safefopen(argv[1],"r"); f2 = safefopen(argv[2],"r"); for (;;) { havec1 = safereadbyte(argv[1],f1,&c1); havec2 = safereadbyte(argv[2],f2,&c2); if (havec1 != havec2) exit_different(); if (!havec1) exit_same(); if (c1 != c2) exit_different(); } }