/* file: pbs-not.c G. Moody 29 February 2012 Read a list of records, write a list of missing records (logical "not") This program must receive two arguments (filenames of a list of all records, and of the list of records to be complemented). */ #include #include #include #define LMAX 128 char **line; FILE **ifile; int n; /* cleanup: close input files, free allocated memory, and quit. */ void cleanup() { if (ifile && ifile[0]) { /* copy remaining missing files to stdout */ while (fgets(line[0], LMAX, ifile[0])) fputs(line[0], stdout); } while (n-- > 0) { fclose(ifile[n]); if (line[n]) free(line[n]); } if (line) free(line); if (ifile) free(ifile); exit(0); } /* init: open input files and read the first line of each. */ void init(int argc, char **argv) { if (argc != 3) /* exactly two inputs required */ exit(1); argc--; argv++; /* skip argv[0] */ ifile = (FILE **)calloc(argc, sizeof(FILE *)); line = (char **)calloc(argc, sizeof(char *)); for (n = 0; n < 2; n++) { if ((ifile[n] = fopen(argv[n], "r")) == NULL) cleanup(); line[n] = (char *)calloc(LMAX, sizeof(char)); } if (fgets(line[1], LMAX, ifile[1]) == NULL) cleanup(); } main(int argc, char **argv) { init(argc, argv); while (1) { int i; if ((i = strcmp(line[0], line[1])) < 0) { fputs(line[0], stdout); if (fgets(line[0], LMAX, ifile[0]) == NULL) cleanup(); } else if (i == 0) { if (fgets(line[1], LMAX, ifile[1]) == NULL || fgets(line[0], LMAX, ifile[0]) == NULL) cleanup(); } else { /* this shouldn't happen! */ if (fgets(line[1], LMAX, ifile[1]) == NULL) cleanup(); } }; cleanup(); }