diff demo/demo_util.c @ 0:e38dacceb958

initial import
author Robert McIntyre <rlm@mit.edu>
date Fri, 21 Oct 2011 05:53:11 -0700
parents
children
line wrap: on
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/demo/demo_util.c	Fri Oct 21 05:53:11 2011 -0700
     1.3 @@ -0,0 +1,57 @@
     1.4 +#include "demo_util.h"
     1.5 +
     1.6 +#include <assert.h>
     1.7 +#include <string.h>
     1.8 +#include <stdlib.h>
     1.9 +#include <stdio.h>
    1.10 +
    1.11 +/* Copyright (C) 2007 Shay Green. This module is free software; you
    1.12 +can redistribute it and/or modify it under the terms of the GNU Lesser
    1.13 +General Public License as published by the Free Software Foundation; either
    1.14 +version 2.1 of the License, or (at your option) any later version. This
    1.15 +module is distributed in the hope that it will be useful, but WITHOUT ANY
    1.16 +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    1.17 +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
    1.18 +details. You should have received a copy of the GNU Lesser General Public
    1.19 +License along with this module; if not, write to the Free Software Foundation,
    1.20 +Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
    1.21 +
    1.22 +unsigned char* load_file( const char* path, long* size_out )
    1.23 +{
    1.24 +	size_t size;
    1.25 +	unsigned char* data;
    1.26 +	
    1.27 +	FILE* in = fopen( path, "rb" );
    1.28 +	if ( !in ) error( "Couldn't open file" );
    1.29 +	
    1.30 +	fseek( in, 0, SEEK_END );
    1.31 +	size = ftell( in );
    1.32 +	if ( size_out )
    1.33 +		*size_out = size;
    1.34 +	rewind( in );
    1.35 +	
    1.36 +	data = (unsigned char*) malloc( size );
    1.37 +	if ( !data ) error( "Out of memory" );
    1.38 +	
    1.39 +	if ( fread( data, 1, size, in ) < size ) error( "Couldn't read file" );
    1.40 +	fclose( in );
    1.41 +	
    1.42 +	return data;
    1.43 +}
    1.44 +
    1.45 +void write_file( const char* path, void const* in, long size )
    1.46 +{
    1.47 +	FILE* out = fopen( path, "wb" );
    1.48 +	if ( !out ) error( "Couldn't create file" );
    1.49 +	if ( (long) fwrite( in, 1, size, out ) < size ) error( "Couldn't write file" );
    1.50 +	fclose( out );
    1.51 +}
    1.52 +
    1.53 +void error( const char* str )
    1.54 +{
    1.55 +	if ( str )
    1.56 +	{
    1.57 +		fprintf( stderr, "Error: %s\n", str );
    1.58 +		exit( EXIT_FAILURE );
    1.59 +	}
    1.60 +}