xref: /plan9/sys/src/ape/lib/ap/stdio/fdopen.c (revision 3e12c5d1bb89fc02707907988834ef147769ddaf)
1 /*
2  * Posix stdio -- fdopen
3  */
4 #include "iolib.h"
5 /*
6  * Open the named file with the given mode, using the given FILE
7  * Legal modes are given below, `additional characters may follow these sequences':
8  * r rb		open to read
9  * w wb		open to write, truncating
10  * a ab		open to write positioned at eof, creating if non-existant
11  * r+ r+b rb+	open to read and write, creating if non-existant
12  * w+ w+b wb+	open to read and write, truncating
13  * a+ a+b ab+	open to read and write, positioned at eof, creating if non-existant.
14  */
fdopen(const int fd,const char * mode)15 FILE *fdopen(const int fd, const char *mode){
16 	FILE *f;
17 	for(f=_IO_stream;f!=&_IO_stream[FOPEN_MAX];f++)
18 		if(f->state==CLOSED)
19 			break;
20 	if(f==&_IO_stream[FOPEN_MAX])
21 		return NULL;
22 	f->fd=fd;
23 	if(mode[0]=='a')
24 		lseek(f->fd, 0L, 2);
25 	if(f->fd==-1) return NULL;
26 	f->flags=0;
27 	f->state=OPEN;
28 	f->buf=0;
29 	f->rp=0;
30 	f->wp=0;
31 	f->lp=0;
32 	return f;
33 }
34