/* fileIO.c */ /* Author: Joey Lesh Date Created: February 17, 2000 This file provides methods to open, close, write a line to, and read a line from a file. */ #include #include #include "llistheader.h" /* initialize(char *, char *) takes a pointer to a string containing the filename to open and a pointer to a string containing a valid mode to open a file in. It returns a FILE pointer to the file. NOTE: If the filename given doesn't exist, the FILE pointer returned will point to NULL. Pre: The file exists. Pre: mode is ("r" || "w" || "a" || "r+" || "w+" || "a+") Post: The file has been opened. */ FILE *initialize(char *filename, char *mode){ FILE *fp; fp = fopen(filename, mode); return fp; }/*intialize(char)*/ /* readLine(FILE *, int) reads a single line from the place in the file referenced by fp. It will read *at maximum* MAXLINELENGTH characters from the line. If there are more characters, the next call to readLine will begin reading at the MAXLINELENGTH character in the line until a '\n' or MAXLINELENGTH characters have been read.Returns a pointer to a char array. Pre: fp points to a valid file opened in "r" or "r+" mode. Post: The fp has been advanced to the next line or the EOF. Post: Memory has been allocated for the char array containing the line that was read in. */ char *readLine(FILE *fp, int MAXLINELENGTH) { int currentchar = 0; int num_chars_read = 0; char *buf; char *charelement; buf = malloc(MAXLINELENGTH); bzero(buf, MAXLINELENGTH); charelement = buf; *charelement++ = (currentchar = fgetc(fp)); /* pretest to see if file is empty */ if (currentchar == EOF) return NULL; /* Return empty string for blank line in the file. */ if (currentchar == '\n') return ""; /* The real work goes on in here. We loop along until an EOF, newline or until we're about to read more characters than our char array can hold, while building the line */ while(((currentchar = (fgetc(fp))) != '\n') && (currentchar != EOF) && (num_chars_read <= MAXLINELENGTH)) { *charelement++ = currentchar; num_chars_read++; } return buf; } /* writeLine(FILE *, char *) writes the characters in buf into the file referenced by fp at the place referenced by fp. Returns 1. Pre: The file was opened in any mode other than "r" Post: A char array has been written to the file Post: fp now points to a different place. */ int writeLine(FILE *fp, char *buf) { int chartowrite; while ((chartowrite = *buf++) != '\0') putc(chartowrite, fp); putc('\n', fp); putc('\0', fp); return 1; } /*closes given file*/ int close(FILE *fp) { return fclose(fp); }