loadfile.cc (1277B)
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 22 void *load_file(const char *fn, unsigned *_sz) { 23 void *data = 0; 24 long sz; 25 FILE *fp; 26 27 if(!(fp = fopen(fn, "rb"))) 28 goto exit; 29 30 if (fseek(fp, 0, SEEK_END)) 31 goto close_and_exit; 32 33 if ((sz = ftell(fp)) < 0) 34 goto close_and_exit; 35 36 if (fseek(fp, 0, SEEK_SET)) 37 goto close_and_exit; 38 39 if (!(data = malloc(sz + 1))) 40 goto close_and_exit; 41 42 if (fread(data, sz, 1, fp) != 1) { 43 free(data); 44 data = 0; 45 } else { 46 ((char*) data)[sz] = 0; 47 if (_sz) 48 *_sz = sz; 49 } 50 51 close_and_exit: 52 fclose(fp); 53 exit: 54 if (!data) 55 fprintf(stderr, "failed to load '%s'\n", fn); 56 return data; 57 }