/* file10 f1 f2 compares the file named f1 to the file named f2. It prints a message saying whether the files have the same contents. If it has any trouble reading the files, it prints an error message on stderr and exits. */ #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); } int main(int argc,char **argv) { FILE *f1; FILE *f2; char c1; char c2; if (argc < 3) { fprintf(stderr,"usage: file10 f1 f2\n"); exit(100); } f1 = fopen(argv[1],"r"); if (!f1) die("open",argv[1]); f2 = fopen(argv[2],"r"); if (!f2) die("open",argv[2]); for (;;) if (fscanf(f1,"%c",&c1) == -1) if (ferror(f1)) die("read",argv[1]); else /* end of file on f1 */ if (fscanf(f2,"%c",&c2) == -1) if (ferror(f2)) die("read",argv[2]); else exit_same(); /* end of file on both f1 and f2 */ else exit_different(); /* end of file on f1, but not f2 */ else if (fscanf(f2,"%c",&c2) == -1) if (ferror(f2)) die("read",argv[2]); else exit_different(); /* end of file on f2, but not f1 */ else if (c1 != c2) exit_different(); }