3
/* Fundamental function to create a new stream.
4
** The argument flags defines the type of stream and the scheme
7
** Written by Kiem-Phong Vo.
11
Sfio_t* sfnew(Sfio_t* oldf, Void_t* buf, size_t size, int file, int flags)
13
Sfio_t* sfnew(oldf,buf,size,file,flags)
14
Sfio_t* oldf; /* old stream to be reused */
15
Void_t* buf; /* a buffer to read/write, if NULL, will be allocated */
16
size_t size; /* buffer size if buf is given or desired buffer size */
17
int file; /* file descriptor to read/write from */
18
int flags; /* type of file stream */
24
SFONCE(); /* initialize mutexes */
32
{ if(f != sfstdin && f != sfstdout && f != sfstderr)
33
f->mutex = NIL(Vtmutex_t*);
37
else if(f->mode&SF_AVAIL)
38
{ /* only allow SF_STATIC to be already closed */
39
if(!(f->flags&SF_STATIC) )
45
{ /* reopening an open stream, close it first */
48
if(((f->mode&SF_RDWR) != f->mode && _sfmode(f,0,0) < 0) ||
52
if(f->data && ((flags&SF_STRING) || size != (size_t)SF_UNBOUND) )
53
{ if(sflags&SF_MALLOC)
54
free((Void_t*)f->data);
55
f->data = NIL(uchar*);
63
{ /* reuse a standard stream structure if possible */
64
if(!(flags&SF_STRING) && file >= 0 && file <= 2)
65
{ f = file == 0 ? sfstdin : file == 1 ? sfstdout : sfstderr;
67
{ if(f->mode&SF_AVAIL)
71
else f = NIL(Sfio_t*);
76
{ if(!(f = (Sfio_t*)malloc(sizeof(Sfio_t))) )
78
SFCLEAR(f, NIL(Vtmutex_t*));
84
f->mutex = vtmtxopen(NIL(Vtmutex_t*), VT_INIT);
87
f->mode = (flags&SF_READ) ? SF_READ : SF_WRITE;
88
f->flags = (flags&SF_FLAGS) | (sflags&(SF_MALLOC|SF_STATIC));
89
f->bits = (flags&SF_RDWR) == SF_RDWR ? SF_BOTH : 0;
91
f->here = f->extent = 0;
92
f->getr = f->tiny[0] = 0;
95
if(size != (size_t)SF_UNBOUND)
97
f->data = size <= 0 ? NIL(uchar*) : (uchar*)buf;
99
f->endb = f->endr = f->endw = f->next = f->data;
102
(*_Sfnotify)(f,SF_NEW,f->file);
104
if(f->flags&SF_STRING)
105
(void)_sfmode(f,f->mode&SF_RDWR,0);