#include #include "linkedlist.h" /* Defines the maximum length of each line read. */ #define Max 80 /* ReadFile takes a string representing a textfile, and returns the lines of it as seperate elements in a doubly-linked list. It will return a single element list, with the element being an error message, if there was an error. */ node *readFile(char *fileName) { /* Sets up a pointer to a doubly-linked list. */ node *linkedList; /* Sets up listItem, used to store the current line from the textfile */ char listItem[Max]; /* Sets up a file pointer. */ FILE *fp; /* Points the file pointer to the filename passed to ReadFile. Returns Null if the file does not exist. */ if ((fp = fopen(fileName, "r")) == NULL) { linkedList = newList("File doesn't exist\n"); return linkedList; } /* Creates a doubly-linked list with each node being a line from the textfile. */ /* Initialize list. */ if ((fgets(listItem, Max, fp)) != NULL) { linkedList = newList(listItem); /* Fill list with data from textfile. */ while ((fgets(listItem, Max, fp)) != NULL) { linkedList = addToEnd(linkedList, listItem); } return linkedList; } else { /* If the file is empty, return a list with "File is empty" as the data for its only node. */ linkedList = newList("File is empty"); return linkedList; } } /* writeFile takes a string representing a filename and a doubly-linked list. It writes the contents of the list to a textfile. It returns 0 if it is successful, and 1 if it is not. */ int writeFile(char * fileName, node *linkedList) { /* Sets up a file pointer. */ FILE *fp; if ((fp = fopen(fileName, "w")) == NULL) { return 1; } else { linkedList = getFirst(linkedList); do { if (fputs(linkedList->data, fp) == NULL) { return 1; } linkedList = getNext(linkedList); } while (!atEnd(linkedList)); return 0; } } /* listPrint takes a doubley linked list with at least one element. It prints the contents of the list to the screen. It assumes that if you want a list item to appear on the next line, you included a newline character in the string. */ void listPrint(node *linkedList) { linkedList = getFirst(linkedList); do { printf("%s", linkedList->data); linkedList = getNext(linkedList); } while (!(atEnd(linkedList))); printf("%s", linkedList->data); }