#include #include #include #include "file_reader.h" static char* filename = NULL; static FILE* f = NULL; static char* currentLine = NULL; static char* currentCharPtr = NULL;; static void fileError() { fprintf(stderr, "Some error reading file '%s'\n", filename); exit(2); } void openFile(const char* fname) { f = fopen(fname, "r"); if ( f == NULL ) fileError(fname); filename = strdup(fname); } char nextChar() { size_t len; if ( f == NULL ) fileError(); if ( currentLine == NULL ) { ssize_t charsRead = getline( ¤tLine, &len, f); if ( charsRead == -1 ) return EOF; currentCharPtr = currentLine; } if ( *currentCharPtr == '\0' ) { free(currentLine); currentCharPtr = currentLine = NULL; return nextChar(); } return *(currentCharPtr++); } void closeFile() { if ( currentLine != NULL ) { free(currentLine); currentLine = NULL; } currentCharPtr = NULL; if ( filename != NULL ) free(filename); filename = NULL; if ( 0 != fclose(f) ) { perror("fclose"); exit(3); } }