view demo/demo_util.c @ 9:477c36226481 tip

added old scripts for historical interest.
author Robert McIntyre <rlm@mit.edu>
date Fri, 21 Oct 2011 07:46:18 -0700
parents e38dacceb958
children
line wrap: on
line source
1 #include "demo_util.h"
3 #include <assert.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <stdio.h>
8 /* Copyright (C) 2007 Shay Green. This module is free software; you
9 can redistribute it and/or modify it under the terms of the GNU Lesser
10 General Public License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version. This
12 module is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15 details. You should have received a copy of the GNU Lesser General Public
16 License along with this module; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
19 unsigned char* load_file( const char* path, long* size_out )
20 {
21 size_t size;
22 unsigned char* data;
24 FILE* in = fopen( path, "rb" );
25 if ( !in ) error( "Couldn't open file" );
27 fseek( in, 0, SEEK_END );
28 size = ftell( in );
29 if ( size_out )
30 *size_out = size;
31 rewind( in );
33 data = (unsigned char*) malloc( size );
34 if ( !data ) error( "Out of memory" );
36 if ( fread( data, 1, size, in ) < size ) error( "Couldn't read file" );
37 fclose( in );
39 return data;
40 }
42 void write_file( const char* path, void const* in, long size )
43 {
44 FILE* out = fopen( path, "wb" );
45 if ( !out ) error( "Couldn't create file" );
46 if ( (long) fwrite( in, 1, size, out ) < size ) error( "Couldn't write file" );
47 fclose( out );
48 }
50 void error( const char* str )
51 {
52 if ( str )
53 {
54 fprintf( stderr, "Error: %s\n", str );
55 exit( EXIT_FAILURE );
56 }
57 }