/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * COPYING NOTES
 *
 * iofile.c -- Advanced I/O file managing functions
 *
 * Copyright (C) 2000 Roberto A. Foglietta <robang@libero.it>
 * Copyright (C) 2002 GEA-Automotive <fogliettar@gea-automotive.com>
 *
 *   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.
 *
 *   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.
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * REVISION NOTES:
 *
 * released 16-10-2002 by Roberto A. Foglietta
 *
 */


#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include "iofile.h"  

#ifdef DEBUG_OUT
# undef DEBUG_OUT
#endif
#define DEBUG_OUT 0
#define PRINTF if(DEBUG_OUT) printf

/***********************************************************************

 	FUNZIONI DI SUPPORTO

***********************************************************************/

FILE *
check_n_openfile (const char *name, const char *mode)
{
	int flag, i, len;
	flag = R_OK | F_OK;
	len = strlen (mode);
	for (i = 0; i < len; i++) {
		if (mode[i] == 'w' || mode[i] == 'a' || mode[i] == '+') {
			flag |= W_OK;
			break;
		}
	}
	if (access (name, flag))
		return NULL;
	else
		return fopen (name, mode);
}


unsigned long
get_file_lenght (FILE * fp)
{
	long lun;
	
	fflush (fp);
	fseek (fp, 0, SEEK_END);
	fflush (fp);
	lun = ftell (fp);
	rewind (fp);
	fflush (fp);
	
	return lun;
}


unsigned char *
read_file_to_buffer (const char *name, const char *mode, long *lun)
{
	FILE *fp;
	unsigned long len;
	unsigned char *buf;
	
	fp = check_n_openfile (name, mode);
	if (fp == NULL)
		return NULL;
	else
		PRINTF ("Aperto il file\n");
	
	len = get_file_lenght (fp);
	if (len <= 0)
		return NULL;
	else
		PRINTF ("lunghezza %ld\n", len);
	
	buf = (unsigned char *) malloc (len);
	if (buf == NULL)
		return NULL;
	else
		PRINTF ("Allocata la memoria\n");
	
	len = (long) read (fileno (fp), buf, (size_t) len);
	PRINTF ("letti %ld bytes\n", len);
	fclose (fp);
	
	if (len <= 0) {
		free (buf);
		buf = NULL;
	} else {
		PRINTF ("Lettura file OK: 0x%lx\n", (unsigned long) buf);
		*lun = len;
	}
	return buf;
}