1 /* Copyright (C) 1991, 1992, 1993, 1996, 1997 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If not,
16 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA. */
26 /* Defined in fopen.c. */
27 extern int __getmode
__P ((const char *mode
, __io_mode
*mptr
));
29 /* Open a new stream that will read and/or write from the buffer in
30 S, which is of LEN bytes. If the mode indicates appending, the
31 buffer pointer is set to point to the first '\0' in the buffer.
32 If S is NULL, the buffer is allocated by malloc and will be freed
33 when the stream is closed. The only purpose of this is to write
34 things and then read what's been written. If LEN is zero, writes will
35 always return errors and reads will always return end-of-file.
37 The stream is set up such that seeks and tells will always fail and
38 once the buffer is full of written characters or empty of characters
39 to read, attempted writes always return an output error and attempted
40 reads always return end-of-file. */
42 fmemopen (s
, len
, mode
)
48 register FILE *stream
;
50 if (!__getmode (mode
, &m
))
53 stream
= __newstream ();
60 stream
->__room_funcs
.__input
= NULL
;
61 /* Output gets error. */
62 stream
->__room_funcs
.__output
= NULL
;
64 /* Do nothing for close. */
65 stream
->__io_funcs
.__close
= NULL
;
66 /* Can't seek outside the buffer. */
67 stream
->__io_funcs
.__seek
= NULL
;
68 /* There is no associated file descriptor to fetch. */
69 stream
->__io_funcs
.__fileno
= NULL
;
73 stream
->__userbuf
= s
!= NULL
&& len
> 0;
80 (void) fclose (stream
);
86 stream
->__buffer
= (char *) s
;
87 stream
->__bufsize
= len
;
89 stream
->__bufp
= stream
->__buffer
;
90 stream
->__get_limit
= (stream
->__buffer
+
91 (stream
->__mode
.__read
? stream
->__bufsize
: 0));
92 stream
->__put_limit
= (stream
->__buffer
+
93 (stream
->__mode
.__write
? stream
->__bufsize
: 0));
94 stream
->__cookie
= NULL
;
96 if (stream
->__mode
.__append
)
98 char *p
= memchr (stream
->__bufp
, '\0',
99 stream
->__get_limit
- stream
->__bufp
);
101 stream
->__bufp
= stream
->__get_limit
;
105 else if (stream
->__mode
.__truncate
)
106 memset ((void *) stream
->__buffer
, 0, len
);