1 /***********************************************************************
3 * This software is part of the ast package *
4 * Copyright (c) 1985-2010 AT&T Intellectual Property *
5 * and is licensed under the *
6 * Common Public License, Version 1.0 *
7 * by AT&T Intellectual Property *
9 * A copy of the License is available at *
10 * http://www.opensource.org/licenses/cpl1.0.txt *
11 * (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9) *
13 * Information and Software Systems Research *
17 * Glenn Fowler <gsf@research.att.com> *
18 * David Korn <dgk@research.att.com> *
19 * Phong Vo <kpv@research.att.com> *
21 ***********************************************************************/
24 /* Fundamental function to create a new stream.
25 ** The argument flags defines the type of stream and the scheme
28 ** Written by Kiem-Phong Vo.
32 Sfio_t
* sfnew(Sfio_t
* oldf
, Void_t
* buf
, size_t size
, int file
, int flags
)
34 Sfio_t
* sfnew(oldf
,buf
,size
,file
,flags
)
35 Sfio_t
* oldf
; /* old stream to be reused */
36 Void_t
* buf
; /* a buffer to read/write, if NULL, will be allocated */
37 size_t size
; /* buffer size if buf is given or desired buffer size */
38 int file
; /* file descriptor to read/write from */
39 int flags
; /* type of file stream */
45 SFONCE(); /* initialize mutexes */
53 { if(f
!= sfstdin
&& f
!= sfstdout
&& f
!= sfstderr
)
54 f
->mutex
= NIL(Vtmutex_t
*);
58 else if(f
->mode
&SF_AVAIL
)
59 { /* only allow SF_STATIC to be already closed */
60 if(!(f
->flags
&SF_STATIC
) )
66 { /* reopening an open stream, close it first */
69 if(((f
->mode
&SF_RDWR
) != f
->mode
&& _sfmode(f
,0,0) < 0) ||
73 if(f
->data
&& ((flags
&SF_STRING
) || size
!= (size_t)SF_UNBOUND
) )
74 { if(sflags
&SF_MALLOC
)
75 free((Void_t
*)f
->data
);
76 f
->data
= NIL(uchar
*);
84 { /* reuse a standard stream structure if possible */
85 if(!(flags
&SF_STRING
) && file
>= 0 && file
<= 2)
86 { f
= file
== 0 ? sfstdin
: file
== 1 ? sfstdout
: sfstderr
;
88 { if(f
->mode
&SF_AVAIL
)
92 else f
= NIL(Sfio_t
*);
97 { if(!(f
= (Sfio_t
*)malloc(sizeof(Sfio_t
))) )
99 SFCLEAR(f
, NIL(Vtmutex_t
*));
105 f
->mutex
= vtmtxopen(NIL(Vtmutex_t
*), VT_INIT
);
108 f
->mode
= (flags
&SF_READ
) ? SF_READ
: SF_WRITE
;
109 f
->flags
= (flags
&SF_FLAGS
) | (sflags
&(SF_MALLOC
|SF_STATIC
));
110 f
->bits
= (flags
&SF_RDWR
) == SF_RDWR
? SF_BOTH
: 0;
112 f
->here
= f
->extent
= 0;
113 f
->getr
= f
->tiny
[0] = 0;
116 if(size
!= (size_t)SF_UNBOUND
)
118 f
->data
= size
<= 0 ? NIL(uchar
*) : (uchar
*)buf
;
120 f
->endb
= f
->endr
= f
->endw
= f
->next
= f
->data
;
123 (*_Sfnotify
)(f
, SF_NEW
, (void*)((long)f
->file
));
125 if(f
->flags
&SF_STRING
)
126 (void)_sfmode(f
,f
->mode
&SF_RDWR
,0);