All pastes #265476 Raw Edit

Stuff

public c v1 · immutable
·published 2006-12-03 09:39 UTC
rendered paste body
/* *  This program is free software; you can redistribute it and/or modify *  it under the terms of the GNU General Public License as published by *  the Free Software Foundation; either version 2 of the License, or *  (at your option) any later version. * *  This program is distributed in the hope that it will be useful, *  but WITHOUT ANY WARRANTY; without even the implied warranty of *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the *  GNU General Public License for more details. * *  You should have received a copy of the GNU General Public License *  along with this program; if not, write to the Free Software *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h>#include <stdlib.h>#include <string.h>#include "room_reader.h"/* *	This is going to read the file character by character, growing the buffer to *  accomodate the data. Once the buffer is done reading (hits the delimiter) it *  flushes the buffer to our array for storage. */int read_room_descriptions(char *rooms_filename, char **room_descriptions) {	char *buffer_a,		*buffer_b,		character;	int buffer_size = DEFAULT_BUFFER_SIZE,		room_number = 0,		buffer_strlen;	FILE *rooms_file;	//we've failed for some reason, return appropriately	if ((rooms_file = fopen(rooms_filename,"r")) == NULL)		return -1;		//start our buffer	buffer_a = memset(malloc(buffer_size * sizeof(char)),'\0',1);	do {		//check to see if we have enough space, if we don't, grow the buffer		if (strlen(buffer_a) >= (buffer_size - 1)) {			buffer_b = buffer_a;			buffer_size *= 2;			buffer_a = memset(malloc(buffer_size * sizeof(char)),'\0',1);			strcpy(buffer_a,buffer_b);			free(buffer_b);		}		//get a character		if (((character = fgetc(rooms_file)) != EOF) && (character != DELIMETER)) {			//no error and no delimeter, add it to the buffer			buffer_strlen = strlen(buffer_a);			buffer_a[buffer_strlen] = character;			buffer_a[buffer_strlen + 1] = '\0';		} else {			//we have an error or the delimeter, flush the buffer			room_descriptions[room_number] = buffer_a;			buffer_size = DEFAULT_BUFFER_SIZE;			buffer_a = memset(malloc(buffer_size * sizeof(char)),'\0',1);			//increment and leave if we've met our room limit			room_number++;			if (room_number >= MAX_ROOMS)				return room_number;		}						} while (!ferror(rooms_file));	//here we met an EOF or error before reaching our room limit	return room_number;}int main(int argc, char **argv) {	//test case		char *filename = "rooms.txt";	char **room_descriptions;	int room_count,i;	room_descriptions = malloc(MAX_ROOMS * sizeof(void));	room_count = read_room_descriptions(filename,room_descriptions);	for (i = 0;i < room_count;i++) {		printf("%s\n",room_descriptions[i]);	}		return 0;}