/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1986
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* $Header:get_whole_file.c 12.0$ */
/* $ACIS:get_whole_file.c 12.0$ */
/* $Source: /ibm/acis/usr/src/ibm/fdb_ca/lib/src/RCS/get_whole_file.c,v $ */

#ifndef lint
static char *rcsid = "$Header:get_whole_file.c 12.0$";
#endif

/* #define debug */
/**********************************************************************\
* 								       *
* Name								       *
* 								       *
* get_whole_file - allocates memory for, and reads in a file	       *
* 								       *
* Synopsis							       *
* 								       *
* int get_whole_file (stream, buffer)				       *
* char *stream;							       *
* char **buffer;						       *
* 								       *
* Description							       *
* 								       *
* get_whole_file allocates memory (using malloc(3) and ralloc(3)) for  *
* stream and reads the file in.  buffer will be set to		       *
* point to the file contents.					       *
* 								       *
* Diagnostics							       *
* 								       *
* +n - normal return, n is the length of the string returned	       *
* -1 - file type is not supported				       *
* -2 - insufficent memory available to hold the file		       *
* -3 - error reading file, buffer will be set to null pointer	       *
* 								       *
\**********************************************************************/

#include <stdio.h>
int get_whole_file (stream, buffer)
FILE *stream;
char **buffer;
{
#define allocation_increment 10 
    int     buffer_size;	/* space allocated so far */
    int     file_size;		/* data read so far */
    int     hunk_size;		/* data read in last read */
    char *malloc(), *realloc();

 /* do initial allocation for buffer */
    *buffer = malloc (allocation_increment);
    file_size = 0;
    buffer_size = allocation_increment;

 /* read file in one block at a time */
    hunk_size = fread (*buffer, 1, buffer_size - (1 + file_size),
	    stream);
#ifdef debug
    printf ("get_whole_file: location 1, hunk_size = %d\n", hunk_size);
#endif
    while (hunk_size > 0) {
	file_size += hunk_size;
	if (buffer_size == (1 + file_size)) {
	/* buffer is full so expand it */
	    buffer_size += allocation_increment;
	    *buffer = realloc (*buffer, buffer_size);
	}
	hunk_size = fread (file_size + *buffer, 1,
		buffer_size - (1 + file_size), stream);
#ifdef debug
        printf ("get_whole_file: location 2, hunk_size = %d\n", hunk_size);
#endif
    }

 /* determin completion reason and return */
    if (hunk_size < 0) {
	printf ("get_whole_file: error reading file\n");
	free (*buffer);
	return - 3;
    }

 /* return unused space in buffer */
    (*buffer) = realloc (*buffer, file_size + 1);

 /* make sure buffer is null terminated */
    (*buffer)[file_size] = '\0';

 /* return file size */
    return file_size;
}
