comparison lib/read-file.c @ 6848:2a11dd9faacd

2006-06-19 Paul Eggert <eggert@cs.ucla.edu> * read-file.c (fread_file): Start with buffer allocation of 0 bytes rather than 1 byte; this simplifies the code. Don't invoke feof; it's not needed. Refactor to avoid duplicate code to free buffer and save/restore errno. (internal_read_file): Remove unused local.
author Simon Josefsson <simon@josefsson.org>
date Wed, 21 Jun 2006 08:02:40 +0000
parents 19c37b3f23b1
children a88f85e4728f
comparison
equal deleted inserted replaced
6847:d65bd1fc3298 6848:2a11dd9faacd
34 *LENGTH. On errors, *LENGTH is undefined, errno preserves the 34 *LENGTH. On errors, *LENGTH is undefined, errno preserves the
35 values set by system functions (if any), and NULL is returned. */ 35 values set by system functions (if any), and NULL is returned. */
36 char * 36 char *
37 fread_file (FILE * stream, size_t * length) 37 fread_file (FILE * stream, size_t * length)
38 { 38 {
39 char *buf = malloc (1); 39 char *buf = NULL;
40 size_t alloc = 1; 40 size_t alloc = 0;
41 size_t size = 0; 41 size_t size = 0;
42 int save_errno;
42 43
43 if (!buf) 44 for (;;)
44 return NULL;
45
46 while (!feof (stream))
47 { 45 {
48 size_t count; 46 size_t count;
47 size_t requested;
49 48
50 if (size + BUFSIZ + 1 > alloc) 49 if (size + BUFSIZ + 1 > alloc)
51 { 50 {
52 char *new_buf; 51 char *new_buf;
53 52
56 alloc = size + BUFSIZ + 1; 55 alloc = size + BUFSIZ + 1;
57 56
58 new_buf = realloc (buf, alloc); 57 new_buf = realloc (buf, alloc);
59 if (!new_buf) 58 if (!new_buf)
60 { 59 {
61 int save_errno = errno; 60 save_errno = errno;
62 free (buf); 61 break;
63 errno = save_errno;
64 return NULL;
65 } 62 }
66 63
67 buf = new_buf; 64 buf = new_buf;
68 } 65 }
69 66
70 count = fread (buf + size, 1, alloc - size - 1, stream); 67 requested = alloc - size - 1;
68 count = fread (buf + size, 1, requested, stream);
71 size += count; 69 size += count;
72 70
73 if (ferror (stream)) 71 if (count != requested)
74 { 72 {
75 int save_errno = errno; 73 save_errno = errno;
76 free (buf); 74 if (ferror (stream))
77 errno = save_errno; 75 break;
78 return NULL; 76 buf[size] = '\0';
77 *length = size;
78 return buf;
79 } 79 }
80 } 80 }
81 81
82 buf[size] = '\0'; 82 free (buf);
83 83 errno = save_errno;
84 *length = size; 84 return NULL;
85
86 return buf;
87 } 85 }
88 86
89 static char * 87 static char *
90 internal_read_file (const char *filename, size_t * length, const char *mode) 88 internal_read_file (const char *filename, size_t * length, const char *mode)
91 { 89 {
92 FILE *stream = fopen (filename, mode); 90 FILE *stream = fopen (filename, mode);
93 char *out; 91 char *out;
94 int save_errno; 92 int save_errno;
95 int rc;
96 93
97 if (!stream) 94 if (!stream)
98 return NULL; 95 return NULL;
99 96
100 out = fread_file (stream, length); 97 out = fread_file (stream, length);