aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ch7/7-06_simple-diff.c81
1 files changed, 81 insertions, 0 deletions
diff --git a/ch7/7-06_simple-diff.c b/ch7/7-06_simple-diff.c
new file mode 100644
index 0000000..ba0c58f
--- /dev/null
+++ b/ch7/7-06_simple-diff.c
@@ -0,0 +1,81 @@
+#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 mygetline(char *line, int max);
+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);
+ }
+}