/* File: list-io.c * Author: Jim Mayfield */ #include #include typedef int list_item_type; #include "lists.h" #include "list-io.h" static void print_int_list_items(FILE *outfile, list_type list) { printf("%d", first(list)); if (!empty_list(rest(list))) { putc(' ', outfile); print_int_list_items(outfile, rest(list)); } } void print_int_list(FILE *outfile, list_type list) { putc('<', outfile); if (!empty_list(list)) print_int_list_items(outfile, list); putc('>', outfile); } static list_type read_int_list_items(FILE *infile) { int item; if (fscanf(infile, "%d", &item) == 1) return(cons(item, read_int_list_items(infile))); else return(the_empty_list); } list_type read_int_list(FILE *infile) { int c; list_type result; while ((c = getc(infile)) != EOF && isspace(c)); if (c == EOF) { fprintf(stderr, "ERROR: end-of-file encountered in read_int_list.\n"); return(the_empty_list); } if (c != '<') { ungetc(c, infile); fprintf(stderr, "ERROR: read_int_list expects lists to begin with '<'.\n" " (A '%c' was found instead).\n", c); return(the_empty_list); } result = read_int_list_items(infile); while ((c = getc(infile)) != EOF && isspace(c)); if (c == EOF) { fprintf(stderr, "ERROR: end-of-file encountered in read_int_list.\n"); return(result); } if (c != '>') { ungetc(c, infile); fprintf(stderr, "ERROR: read_int_list expects lists to end with '>'.\n" " (A '%c' was found instead).\n", c); return(result); } return(result); }