/* File: stringlistio.c * Author: Samuel A. Rebelsky * Version: 1.0 of February 2000 * * I/O routines for simple lists of strings. Written as a client of * the other list utilities so that the system is more modular (and * so that I implicitly test all those routines). Part of an examples * for CSC364 2000S. * * Provides: * dumpList(stringlist, fileName) * write a list to a file * printlist(FILE *, stringlist) * write a list to a file * readList(fileName) * read a list from a file */ /*********** * Headers * *****************************************************************/ #include #include "stringlist.h" /******************** * Exported Methods * *****************************************************************/ /* Dump a list to a file. */ void dumpList(char *fname, stringlist stuff) { FILE *dest; /* The file that will contain the elements. */ /* Set up the file for writing. */ dest = fopen(fname, "w"); /* Sanity check. */ if (dest == NULL) return; /* Print the list. */ printList(dest, stuff); /* Clean up. */ fclose(dest); } /* dumpList() */ /* Print a list. */ void printList(FILE *dest, stringlist stuff) { char *str; /* One string in the list. */ /* Scan through the list, printing as you go. */ reset(stuff); while ((str = nextElement(stuff)) != NULL) fprintf(dest, "%s\n", str); } /* printList() */ /* Read a list from a file. */ stringlist readList(char *fname) { FILE *source; /* The file that contains the elements. */ stringlist stuff; /* The list we're building. */ char str[MAXSTRING]; /* A buffer for reading strings. */ /* Open the file to prepare for reading. */ source = fopen(fname, "r"); /* Sanity check. */ if (source == NULL) return NULL; /* Prepare the list. */ stuff = newList(); /* Sanity check. */ if (stuff == NULL) { fclose(source); return NULL; } /* Read all the lines. */ while (fgets(str,MAXSTRING,source)) { if (!addToEnd(stuff, str)) { // Whoops! Failed to add. clear(stuff); freeList(stuff); fclose(source); return NULL; } } /* while there are strings to read */ /* Clean up. */ fclose(source); return stuff; } /* readList() */