loadfile.cc (1293B)
1 /* Copyright 2013 Brian Swetland <swetland@frotz.net> 2 * 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include <stdio.h> 17 #include <stdlib.h> 18 #include <string.h> 19 20 #include "util.h" 21 #include "io.h" 22 23 void *load_file(const char *fn, unsigned *_sz) { 24 void *data = 0; 25 long sz; 26 FILE *fp; 27 28 if (!(fp = io_fopen_asset(fn, "file"))) 29 goto exit; 30 31 if (fseek(fp, 0, SEEK_END)) 32 goto close_and_exit; 33 34 if ((sz = ftell(fp)) < 0) 35 goto close_and_exit; 36 37 if (fseek(fp, 0, SEEK_SET)) 38 goto close_and_exit; 39 40 if (!(data = malloc(sz + 1))) 41 goto close_and_exit; 42 43 if (fread(data, sz, 1, fp) != 1) { 44 free(data); 45 data = 0; 46 } else { 47 ((char*) data)[sz] = 0; 48 if (_sz) 49 *_sz = sz; 50 } 51 52 close_and_exit: 53 fclose(fp); 54 exit: 55 if (!data) 56 error("Failed to load '%s'", fn); 57 return data; 58 }