aboutsummaryrefslogtreecommitdiff
path: root/ch7/7-06_simple-diff.c
blob: ddd28dd2ed22d60bb8a75f7bd4b5ebbf581cffcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* The C Programming Language: 2nd Edition
 *
 * Exercise 7-6: Write a program to compare two files, printing the first line
 * where they differ.
 *
 * Notes: `cat` is a surprisingly small program, and that trend continues with
 * this little `diff` rip-off. This could probably be done with sparing,
 * careful use of 'goto', but that's generally in the realm of "you better know
 * what you're doing". I feel that the code explains itself here.
 */

#define LINE_MAX 200

int max(int x, int y);

int main(int argc, char *argv[]) {
	/* Setup the file pointers so we can iterate through them */
	FILE *fileA;
	FILE *fileB;
	char *prog = argv[0];
	char line1[LINE_MAX];
	char line2[LINE_MAX];
	int len1 = 0;
	int len2 = 0;
	int done = 0;
	if (argc != 3) {
		fprintf(stderr, "%s: you must compare two files.\n", prog);
		exit(1);
	}
	/* Setup our file pointers */
	if ((fileA = fopen(argv[1], "r")) == NULL) {
		fprintf(stderr, "%s: could not open file '%s'\n", prog, argv[1]);
		exit(2);
	}
	if ((fileB = fopen(argv[2], "r")) == NULL) {
		fprintf(stderr, "%s: could not open file '%s'\n", prog, argv[2]);
		exit(2);
	}
	while (done == 0) {
		len1 = fetchline(fileA, line1, LINE_MAX);
		len2 = fetchline(fileB, line2, LINE_MAX);
		if (len1 == 0 || len2 == 0) {
			break;
		}
		/* If their length is different, then the lines themselves are
		 * different */
		if (len1 != len2) {
			done = 1;
			break;
		}
		/* Basic string comparison's all we need to determine if there's a
		 * match or not. */
		if (strcmp(line1, line2) != 0) {
			done = 1;
			break;
		}
	}
	if (done != 0) {
		printf("These lines do not match:\n");
		printf("%20s: %s%20s: %s", argv[1], line1, argv[2], line2);
		return 0;
	}
}

int max(int x, int y) {
	return (x > y) ? x : y;
}

/* Stealing this from the book because it makes life simpler */
int fetchline(FILE *fp, char *line, int max) {
	if (fgets(line, max, fp) == NULL) {
		return 0;
	} else {
		return strlen(line);
	}
}