1 /* read-file.c -- read file contents into a string
2 Copyright (C) 2006 Free Software Foundation, Inc.
3 Written by Simon Josefsson and Bruno Haible.
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; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
23 #include "read-file.h"
25 /* Get realloc, free. */
31 /* Read a STREAM and return a newly allocated string with the content,
32 and set *LENGTH to the length of the string. The string is
33 zero-terminated, but the terminating zero byte is not counted in
34 *LENGTH. On errors, *LENGTH is undefined, errno preserves the
35 values set by system functions (if any), and NULL is returned. */
37 fread_file (FILE * stream, size_t * length)
49 if (size + BUFSIZ + 1 > alloc)
54 if (alloc < size + BUFSIZ + 1)
55 alloc = size + BUFSIZ + 1;
57 new_buf = realloc (buf, alloc);
67 requested = alloc - size - 1;
68 count = fread (buf + size, 1, requested, stream);
71 if (count != requested)
88 internal_read_file (const char *filename, size_t * length, const char *mode)
90 FILE *stream = fopen (filename, mode);
97 out = fread_file (stream, length);
101 if (fclose (stream) != 0)
115 /* Open and read the contents of FILENAME, and return a newly
116 allocated string with the content, and set *LENGTH to the length of
117 the string. The string is zero-terminated, but the terminating
118 zero byte is not counted in *LENGTH. On errors, *LENGTH is
119 undefined, errno preserves the values set by system functions (if
120 any), and NULL is returned. */
122 read_file (const char *filename, size_t * length)
124 return internal_read_file (filename, length, "r");
127 /* Open (on non-POSIX systems, in binary mode) and read the contents
128 of FILENAME, and return a newly allocated string with the content,
129 and set LENGTH to the length of the string. The string is
130 zero-terminated, but the terminating zero byte is not counted in
131 the LENGTH variable. On errors, *LENGTH is undefined, errno
132 preserves the values set by system functions (if any), and NULL is
135 read_binary_file (const char *filename, size_t * length)
137 return internal_read_file (filename, length, "rb");