xref: /plan9-contrib/sys/src/ape/lib/ap/stdio/freopen.c (revision 7dd7cddf99dd7472612f1413b4da293630e6b1bc)
1 /*
2  * pANS stdio -- freopen
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  */
15 FILE *freopen(const char *nm, const char *mode, FILE *f){
16 	if(f->state!=CLOSED) fclose(f);
17 	if(mode[1]=='+' || mode[2]=='+'){
18 		if(mode[0]=='w') close(creat(nm, 0666));
19 		f->fd=open(nm, O_RDWR);
20 		if(f->fd==-1){
21 			close(creat(nm, 0666));
22 			f->fd=open(nm, O_RDWR);
23 		}
24 		if(mode[0]=='a') lseek(f->fd, 0L, 2);
25 	}
26 	else{
27 		switch(mode[0]){
28 		default: return NULL;
29 		case 'r':
30 			f->fd=open(nm, O_RDONLY);
31 			break;
32 		case 'w':
33 			f->fd=creat(nm, 0666);
34 			break;
35 		case 'a':
36 			f->fd=open(nm, O_WRONLY);
37 			if(f->fd==-1)
38 				f->fd=creat(nm, 0666);
39 			lseek(f->fd, 0L, 2);
40 			break;
41 		}
42 	}
43 	if(f->fd==-1) return NULL;
44 	f->flags=(mode[0]=='a')? APPEND : 0;
45 	f->state=OPEN;
46 	f->buf=0;
47 	f->rp=0;
48 	f->wp=0;
49 	f->lp=0;
50 	return f;
51 }
52