aboutsummaryrefslogtreecommitdiff
path: root/ch7
diff options
context:
space:
mode:
authorzlg <zlg@zlg.space>2016-11-17 07:34:18 -0800
committerzlg <zlg@zlg.space>2016-11-17 07:34:18 -0800
commit54b3475b3041bf35c25bfad2f521d5751e6eadbf (patch)
tree065a39b4c5b01ff48374944ac58ab2f94d0bbf71 /ch7
parentActually run astyle on the file... (diff)
downloadknr-54b3475b3041bf35c25bfad2f521d5751e6eadbf.tar.gz
knr-54b3475b3041bf35c25bfad2f521d5751e6eadbf.tar.bz2
knr-54b3475b3041bf35c25bfad2f521d5751e6eadbf.tar.xz
knr-54b3475b3041bf35c25bfad2f521d5751e6eadbf.zip
Solve Exercise 7-6: simple `diff` utility
Diffstat (limited to 'ch7')
-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);
+ }
+}