/* Note on the construction x = realloc(x,...) used here: If realloc fails, it returns 0, and we lose the old value of x. Memory leak! This would be bad if we were doing anything other than exiting. This program assumes that each line is terminated by a newline. Can you modify it so that it works for a final line without a newline? */ #include #include #include #include void die(void) { fprintf(stderr,"Something went wrong!\n"); exit(111); } FILE *f[2]; int haveline[2] = { 0, 0 }; char *x[2] = { 0, 0 }; int xlen[2] = { 0, 0 }; int xspace[2] = { 0, 0 }; void getline(int i) { char c; xlen[i] = 0; for (;;) { if (fscanf(f[i],"%c",&c) == -1) { if (ferror(f[i]) == 1) die(); haveline[i] = 0; return; } if (c == '\n') { haveline[i] = 1; return; } if (xlen[i] == xspace[i]) { xspace[i] = xspace[i] * 2 + 1; x[i] = realloc(x[i],xspace[i]); if (!x[i]) die(); } x[i][xlen[i]++] = c; } } void printline(int i) { int j; for (j = 0;j < xlen[i];++j) putchar(x[i][j]); putchar('\n'); getline(i); } int smallerline(void) { int j = 0; if (!haveline[0]) return 1; if (!haveline[1]) return 0; for (;;) { if (j == xlen[0]) return 0; if (j == xlen[1]) return 1; if (x[0][j] < x[1][j]) return 0; if (x[0][j] > x[1][j]) return 1; ++j; } } int main(int argc,char **argv) { if (argc < 3) die(); ++argv; f[0] = fopen(argv[0],"r"); if (!f[0]) die(); f[1] = fopen(argv[1],"r"); if (!f[1]) die(); getline(0); getline(1); while (haveline[0] || haveline[1]) printline(smallerline()); exit(0); }