|
| 1 | +/* |
| 2 | + * Exercise 7-6. Write a program to compare two file, printing the first line |
| 3 | + * where they differ. |
| 4 | + * By Faisal Saadatmand |
| 5 | + */ |
| 6 | + |
| 7 | +#define MAXFILES 3 |
| 8 | +#define MAXLEN 1000 |
| 9 | + |
| 10 | +#include <stdio.h> |
| 11 | +#include <stdlib.h> |
| 12 | +#include <string.h> |
| 13 | + |
| 14 | +/* functions */ |
| 15 | +int getLine(FILE *, char *, int); |
| 16 | + |
| 17 | +/* getLine: read line, return length - fgets version */ |
| 18 | +int getLine(FILE *fp, char *line, int max) |
| 19 | +{ |
| 20 | + if (fgets(line, max, fp) == NULL) |
| 21 | + return 0; |
| 22 | + else |
| 23 | + return strlen(line); |
| 24 | +} |
| 25 | + |
| 26 | +int main(int argc, char *argv[]) |
| 27 | +{ |
| 28 | + FILE *file[MAXFILES]; /* array to store files */ |
| 29 | + char *prog = argv[0]; /* program name for errors */ |
| 30 | + char *f1name = argv[1]; /* file 1 name for printing line */ |
| 31 | + char *f2name = argv[2]; /* file 2 name for printing line */ |
| 32 | + char f1line[MAXLEN], f2line[MAXLEN]; /* currently read line */ |
| 33 | + int f1ln, f2ln; /* currently read line number */ |
| 34 | + int result, i; |
| 35 | + |
| 36 | + if (argc != 3) { /* wrong format */ |
| 37 | + fprintf(stderr, "Use: %s file1 file2\n", prog); |
| 38 | + exit(EXIT_FAILURE); |
| 39 | + } |
| 40 | + |
| 41 | + /* open files */ |
| 42 | + for (i = 1; --argc > 0; ++i) /* skip file[0] for readability */ |
| 43 | + if ((file[i] = fopen(*++argv, "r")) == NULL) { |
| 44 | + fprintf(stderr, "%s: can't open %s\n", prog, *argv); |
| 45 | + exit(EXIT_FAILURE); |
| 46 | + } |
| 47 | + |
| 48 | + f1ln = f2ln = result = 0; |
| 49 | + while (!feof(file[1]) || !feof(file[2])) { |
| 50 | + if (getLine(file[1], f1line, MAXLEN) > 0) |
| 51 | + f1ln++; /* count successfully read lines */ |
| 52 | + if (getLine(file[2], f2line, MAXLEN) > 0) |
| 53 | + f2ln++; /* count successfully read lines */ |
| 54 | + |
| 55 | + if ((result = strcmp(f1line, f2line)) != 0) |
| 56 | + break; /* found mismatching line */ |
| 57 | + } |
| 58 | + |
| 59 | + if (result != 0) { |
| 60 | + fprintf(stdout, "%s: %i: %s", f1name, f1ln, f1line); |
| 61 | + fprintf(stdout, "%s: %i: %s", f2name, f2ln, f2line); |
| 62 | + } else |
| 63 | + printf("%s and %s are identical\n", f1name, f2name); |
| 64 | + |
| 65 | + fclose(file[1]); |
| 66 | + fclose(file[2]); |
| 67 | + |
| 68 | + exit(EXIT_SUCCESS); |
| 69 | +} |
0 commit comments