/* Program: MERGE.C Author : Kim Moser Date : 19 January, 1991 System : IBM PC / Borland Turbo C 2.0 Descrip: Given two files of sorted words, merges them to stdout. If any words are duplicated, then takes the marked one, if any. */ #include #include #include #define MAX_LEN 80 /* Max word len */ static void usage(void); static void usage(void) { fputs("\ usage: MERGE []\n\ If is specified, then all words that are in file2 but not in file1\n\ will be sent to .\n\ ", stderr); exit(-1); } static void readword(FILE *fp, char *dest, int *marked); static void readword(FILE *fp, char *dest, int *marked) { if (fgets(dest, MAX_LEN, fp) == NULL) { dest[0] = '\0'; *marked = 0; } else { dest[strlen(dest)-1] = '\0'; *marked = (dest[strlen(dest)-1] == '*'); if (*marked) { dest[strlen(dest)-1] = '\0'; } } } static void outword(char *word, int marked); static void outword(char *word, int marked) { printf("%s%s\n", word, (marked?"*":"")); } static FILE *NOTEFILE = NULL; static void note(char *s); static void note(char *s) { if (NOTEFILE != NULL) { fprintf(NOTEFILE, "%s\n", s); } } static void finishfile(FILE *fp, int note_yn); static void finishfile(FILE *fp, int note_yn) { char tmpword[MAX_LEN]; int tmpint; while (1) { readword(fp, tmpword, &tmpint); if (!tmpword[0]) break; outword(tmpword, tmpint); if (note_yn) note(tmpword); } } void main(int argc, char **argv) { FILE *fp1, *fp2; char *fname1, *fname2; int marked1, marked2; char word1[MAX_LEN], word2[MAX_LEN]; char *notefilename=NULL; if (argc < 3 || argc > 4) usage(); fname1 = argv[1]; fname2 = argv[2]; if ((fp1 = fopen(fname1, "r")) == NULL) { usage(); } if ((fp2 = fopen(fname2, "r")) == NULL) { usage(); } if (argc >= 4) { notefilename = argv[3]; if ((NOTEFILE = fopen(notefilename, "w")) == NULL) { usage(); } } readword(fp1, word1, &marked1); readword(fp2, word2, &marked2); while (word1[0] || word2[0]) { if (!word1[0]) { outword(word2, marked2); note(word2); finishfile(fp2, 1); break; } else if (!word2[0]) { outword(word1, marked1); finishfile(fp1, 0); break; } if (!strcmp(word1, word2)) { /* Words are identical, so if either word is marked, output it, otherwise output either. */ if (marked1) { outword(word1, marked1); } else { outword(word2, marked2); } readword(fp1, word1, &marked1); readword(fp2, word2, &marked2); } else { if (strcmp(word1, word2) < 0) { /* word1 < word2 */ outword(word1, marked1); readword(fp1, word1, &marked1); } else { outword(word2, marked2); note(word2); readword(fp2, word2, &marked2); } } } if (fclose(fp1)) { fprintf(stderr, "Error closing file '%s'.\n", fname1); } if (fclose(fp2)) { fprintf(stderr, "Error closing file '%s'.\n", fname2); } if (notefilename != NULL) { if (fclose(NOTEFILE)) { fprintf(stderr, "Error closing note file '%s'.\n", notefilename); } } exit(0); }