Added a basic implementation of wc.
[4chanprog.git] / coreutils / cmp.c
blobe113aa6b139408a4422bcef0e617bc7c50b534af
1 /* @cmp.c */
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <string.h>
7 #include <unistd.h>
9 #define CMP_BUFSIZE 65536
11 char buf1[CMP_BUFSIZE];
12 char buf2[CMP_BUFSIZE];
14 int main(int argc, char **argv) {
15 int c,lflag=0,sflag=0,ret=0;
16 int linenum=1,bytenum=1;
17 int l1,l2;
18 int i;
19 FILE *f1, *f2;
20 while((c=getopt(argc,argv,"ls"))!=-1) {
21 if(c=='l')
22 lflag=1;
23 else if(c=='s')
24 sflag=1;
25 else {
26 fprintf(stderr,"%s: unrecognised option '%c'\n",argv[0],optopt);
27 return 2;
30 if(sflag&&lflag) {
31 fprintf(stderr,"%s: s and l options are mutually exclusive\n",argv[0]);
32 return 2;
34 if(argc-optind<2) {
35 fprintf(stderr,"usage: %s [-l | -s] file1 file2\n",argv[0]);
36 return 2;
38 if(!(f1=fopen(argv[optind++],"rb"))||!(f2=fopen(argv[optind++],"rb"))) {
39 fprintf(stderr,"%s: cannot open %s: %s\n",argv[0],argv[optind-1],strerror(errno));
40 return 2;
42 while((l1=fread(buf1,1,CMP_BUFSIZE,f1))&&(l2=fread(buf2,1,CMP_BUFSIZE,f2))) {
43 for(i=0;l1&&l2;i++,l1--,l2--) {
44 if(buf1[i]!=buf2[i]) {
45 if(!sflag) {
46 if(!lflag) {
47 printf("%s %s differ: char %d, line %d\n",argv[optind-2],argv[optind-1],bytenum+i,linenum);
48 return_differ:
49 fclose(f1);
50 fclose(f2);
51 return 1;
52 } else
53 printf("%d %o %o\n",bytenum+i,buf1[i],buf2[i]);
55 ret=1;
57 if(buf1[i]=='\n') linenum++;
59 if(l1 && !sflag) {
60 printf("cmp: EOF on %s\n",argv[optind-1]);
61 goto return_differ;
62 } else if(l2 && !sflag) {
63 printf("cmp: EOF on %s\n",argv[optind-2]);
64 goto return_differ;
66 bytenum+=l1;
68 fclose(f1);
69 fclose(f2);
70 return ret;