/* Program: MERGEALL.C Author : Kim Moser Date : 19 January, 1991 System : IBM PC / Borland Turbo C 2.0 Descrip: Acts on files of words, "a.txt", "b.txt", "c.txt" ... "z.txt". First searches for words of length 1, then 2, then 3, etc. (Stops when no words found in pass.) For each pass, writes (sorted) words found from each file to file "n.out" where 'n' is the length of the words in that file. E.g. given files: A.TXT: B.TXT C.TXT A BE C AARON BORE CAT APPLE BARN CONE ARGH CY Produces files: 1.OUT 2.OUT 3.OUT 4.OUT 5.OUT A BE CAT ARGH AARON C CY BORE APPLE BARN CONE Usage : MERGEALL */ #include #include #include #define MAX_LEN 28 /* Max word len */ static int LENGTH; /* Current length being worked on */ #define BUF_SIZE 100 static char words[26][BUF_SIZE]; static long int fps[26]; /* Last file positions */ static FILE *OUTFILE; static char OUTFILENAME[40]; static void initvars(void); static void initvars(void) /* Initialize variables */ { int i; for (i=0; i<26; i++) { words[i][0] = '\0'; fps[i] = 0; } } static void readnext(int i); static void readnext(int i) /* Reads next word of length LENGTH from file ".txt". */ { FILE *fp; char *fname = "?.txt"; if (fps[i] == -1L) return; fname[0] = i + 'A'; if ((fp = fopen(fname, "r")) == NULL) { fprintf(stderr, "fopen() failed for file '%s'.\n", fname); exit(-1); } if (fseek(fp, fps[i], SEEK_SET)) { fprintf(stderr, "fseek() failed for file '%s' (pos=%ld).\n", fname, fps[i]); exit(-1); } do { if (fgets(words[i], BUF_SIZE, fp) == NULL) { words[i][0] = '\0'; break; } /* Remove trailing newline: */ words[i][strlen(words[i])-1] = '\0'; /* fprintf(stderr, "%s\n", words[i]); */ } while (strlen(words[i]) != LENGTH); if (words[i][0]) { if ((fps[i] = ftell(fp)) == -1L) { fprintf(stderr, "ftell() failed for '%s'.\n", fname); exit(-1); } } else { fps[i] = -1L; } if (fclose(fp)) { fprintf(stderr, "fclose() failed for '%s'.\n", fname); exit(-1); } } static int out(void); static int out(void) /* Find "smallest" (alphabetically) word, output it, and read next word (of length LENGTH) from file that it came from. Returns whether there are any words. */ { int i; /* Start 'smallest' at first non-empty word: */ for (i=0; i<26 && !words[i][0]; i++); if (i >= 26) return (0); fprintf(OUTFILE, "%s\n", words[i]); readnext(i); #if 0 /* Now find smallest: */ for (i=smallest+1; i<26; i++) { if (words[i][0] && (strcmp(words[i], words[smallest]) < 0)) smallest = i; } fprintf(OUTFILE, "%s\n", words[smallest]); readnext(words[smallest][0]-'A'); #endif return (1); } void main(void) { int i; unsigned long count; for (LENGTH=1; LENGTH