#include #include int main(int argc, char **argv) { int i, first, noneof_count; FILE **fp; int *data, *eof; extern void *emalloc(unsigned size); /* get rid of argv[0] */ argc--; argv++; /* allocate all storage */ fp = (FILE **)emalloc(argc * sizeof(FILE *)); data = (int *)emalloc(argc * sizeof(int)); eof = (int *)emalloc(argc * sizeof(int)); /* open files and pre-load */ noneof_count = 0; for (i = 0; i < argc; i++) { if ((fp[i] = fopen(argv[i], "r")) == NULL) { perror(argv[i]); return 1; } eof[i] = fscanf(fp[i], "%d", &data[i]); if (eof[i] != EOF) noneof_count++; } /* merge */ while (noneof_count) { /* find first number out of the non-eof files' next numbers */ first = -1; for (i = 0; i < argc; i++) if (eof[i] != EOF && (first == -1 || data[i] < data[first])) first = i; /* output and reload */ printf("%d\n", data[first]); eof[first] = fscanf(fp[first], "%d", &data[first]); if (eof[first] == EOF) noneof_count--; } return 0; } void *emalloc(unsigned size) { void *p = malloc(size); if (p == NULL) { fprintf(stderr, "out of memory!\n"); exit(1); } return p; }