Adding upstream version 3.30~pre4.
[syslinux-debian/hramrach.git] / com32 / libutil / loadfile.c
blobd9cfb3b7d40b8271f48095520175f396289425d0
1 /* ----------------------------------------------------------------------- *
3 * Copyright 2005 H. Peter Anvin - All Rights Reserved
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, Inc., 53 Temple Place Ste 330,
8 * Boston MA 02111-1307, USA; either version 2 of the License, or
9 * (at your option) any later version; incorporated herein by reference.
11 * ----------------------------------------------------------------------- */
14 * loadfile.c
16 * Read the contents of a data file into a malloc'd buffer
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <string.h>
23 #include <fcntl.h>
24 #include <sys/stat.h>
26 #include "loadfile.h"
28 int loadfile(const char *filename, void **ptr, size_t *len)
30 int fd;
31 struct stat st;
32 void *data;
33 FILE *f;
34 size_t xlen;
36 fd = open(filename, O_RDONLY);
37 if ( fd < 0 )
38 return -1;
40 f = fdopen(fd, "rb");
41 if ( !f ) {
42 close(fd);
43 return -1;
46 if ( fstat(fd, &st) )
47 goto err_fclose;
49 *len = st.st_size;
50 xlen = (st.st_size + LOADFILE_ZERO_PAD-1) & ~(LOADFILE_ZERO_PAD-1);
52 *ptr = data = malloc(xlen);
53 if ( !data )
54 goto err_fclose;
56 if ( (off_t)fread(data, 1, st.st_size, f) != st.st_size )
57 goto err_free;
59 memset((char *)data + st.st_size, 0, xlen-st.st_size);
61 fclose(f);
62 return 0;
64 err_free:
65 free(data);
66 err_fclose:
67 fclose(f);
68 return -1;