summaryrefslogtreecommitdiff
path: root/com32/libutil/loadfile.c
blob: d9cfb3b7d40b8271f48095520175f396289425d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2005 H. Peter Anvin - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 53 Temple Place Ste 330,
 *   Boston MA 02111-1307, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * loadfile.c
 *
 * Read the contents of a data file into a malloc'd buffer
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "loadfile.h"

int loadfile(const char *filename, void **ptr, size_t *len)
{
  int fd;
  struct stat st;
  void *data;
  FILE *f;
  size_t xlen;

  fd = open(filename, O_RDONLY);
  if ( fd < 0 )
    return -1;

  f = fdopen(fd, "rb");
  if ( !f ) {
    close(fd);
    return -1;
  }

  if ( fstat(fd, &st) )
    goto err_fclose;

  *len = st.st_size;
  xlen = (st.st_size + LOADFILE_ZERO_PAD-1) & ~(LOADFILE_ZERO_PAD-1);

  *ptr = data = malloc(xlen);
  if ( !data )
    goto err_fclose;

  if ( (off_t)fread(data, 1, st.st_size, f) != st.st_size )
    goto err_free;

  memset((char *)data + st.st_size, 0, xlen-st.st_size);

  fclose(f);
  return 0;

 err_free:
  free(data);
 err_fclose:
  fclose(f);
  return -1;
}