/* filestuff.c * Authors: Pete Broadwell * Josh Vickery * this program contains functions for reading a list from a file, * and for printing a list to a file or to an output stream. */ #include "ll_defs.h" /* read a list from a file, return a pointer to a linked list /* this fuction is called from within the main interactive loop * of fun_with_lists and requires that it be passed the name of * the file to be opened. */ llist *readfile(char *file) { /* variable declarations */ FILE *fd; char buf[256]; int len; node *current_node; llist *current_list; /* try to open the file, exit on failure */ fd=fopen(file, "r"); if (fd == NULL) { printf("Filename does not exist.\n"); exit(1); } /* read the first line of the buffer into a new node */ if (fgets(buf, sizeof(buf), fd) == NULL) printf("Unable to read from file.\n"); len=strlen(buf); buf[len-1]='\0'; current_node=(node *) create_n(buf); /* create a new linked list, with this node as the first, last and cursor */ current_list=(llist *) create_l(current_node); /* add the remaining lines in the file to the list */ while (fgets(buf, sizeof(buf), fd) != NULL) { len=strlen(buf); buf[len-1]='\0'; current_node=(node *) create_n(buf); current_list=(llist *)add_to_end(current_list, current_node); } return(current_list); } /* write a list to a file or the screen, take a file pointer and llist * pointer. Since this can take standard out, the file must be open * This function is called from the main loop of fun_with_lists */ writefile(FILE *fp, llist *clist) { /* this line checks, among other things, that we're not trying to print * a list on which all elments have been deleted (because in this * implementation, such a list still contains one element, which is * NULL, but you obviously can't print that out. */ if ((clist!=NULL) && ((clist->first!=NULL) && (clist->last!=NULL))) { /* move the cursor to the front of the list */ clist->current=(node *)tofront(clist); /* step through the list and print each element */ while (clist->current != clist->last) { fprintf(fp, "%s\n", clist->current->contents); clist->current = (node *)advance_cursor(clist); } fprintf(fp, "%s\n", clist->current->contents); clist->current=(node *)tofront(clist); } }