~ubuntu-branches/ubuntu/hardy/klibc/hardy-updates

« back to all changes in this revision

Viewing changes to usr/kinit/readfile.c

  • Committer: Bazaar Package Importer
  • Author(s): Jeff Bailey
  • Date: 2006-01-04 20:24:52 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20060104202452-ec4v3n829rymukuv
Tags: 1.1.15-0ubuntu1
* New upstream version.

* Patch to fix compilation on parisc64 kernels.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * readfile.c
 
3
 *
 
4
 * Read the entire contents of a file into malloc'd storage.  This
 
5
 * is mostly useful for things like /proc files where we can't just
 
6
 * fstat() to get the length and then mmap().
 
7
 *
 
8
 * Returns the number of bytes read, or -1 on error.
 
9
 */
 
10
 
 
11
#include <stdlib.h>
 
12
#include <stdio.h>
 
13
#include <errno.h>
 
14
#include <sys/stat.h>
 
15
 
 
16
ssize_t freadfile(FILE *f, char **pp)
 
17
{
 
18
  size_t bs;                    /* Decent starting point... */
 
19
  size_t bf;                    /* Bytes free */
 
20
  size_t bu = 0;                /* Bytes used */
 
21
  char *buffer, *nb;
 
22
  size_t rv;
 
23
  int old_errno = errno;
 
24
#if 0
 
25
  struct stat st;
 
26
 
 
27
  if ( !fstat(fileno(f), &st) && S_ISREG(st.st_mode) && st.st_size )
 
28
    bs = st.st_size+1;
 
29
  else
 
30
#endif
 
31
    bs = BUFSIZ;                /* A guess as good as any */
 
32
 
 
33
  bf = bs;
 
34
  buffer = malloc(bs);
 
35
 
 
36
  if ( !buffer )
 
37
    return -1;
 
38
  
 
39
  for (;;) {
 
40
    errno = 0;
 
41
 
 
42
    while ( bf && (rv = _fread(buffer+bu, bf, f)) ) {
 
43
      bu += rv;
 
44
      bf -= rv;
 
45
    }
 
46
  
 
47
    if ( errno && errno != EINTR && errno != EAGAIN ) {
 
48
      /* error */
 
49
      free(buffer);
 
50
      return -1;
 
51
    }
 
52
 
 
53
    if ( bf ) {
 
54
      /* Hit EOF, no error */
 
55
 
 
56
      /* Try to free superfluous memory */
 
57
      if ( (nb = realloc(buffer, bu+1)) )
 
58
        buffer = nb;
 
59
 
 
60
      /* Null-terminate result for good measure */
 
61
      buffer[bu] = '\0';
 
62
 
 
63
      *pp = buffer;
 
64
      errno = old_errno;
 
65
      return bu;
 
66
    }
 
67
 
 
68
    /* Double the size of the buffer */
 
69
    bf += bs;
 
70
    bs += bs;
 
71
    if ( !(nb = realloc(buffer, bs)) ) {
 
72
      /* out of memory error */
 
73
      free(buffer);
 
74
      return -1;
 
75
    }
 
76
    buffer = nb;
 
77
  }
 
78
}
 
79
 
 
80
ssize_t readfile(const char *filename, char **pp)
 
81
{
 
82
  FILE *f = fopen(filename, "r");
 
83
  ssize_t rv;
 
84
 
 
85
  if ( !f )
 
86
    return -1;
 
87
 
 
88
  rv = freadfile(f, pp);
 
89
 
 
90
  fclose(f);
 
91
 
 
92
  return rv;
 
93
}