xref: /plan9/sys/src/libstdio/freopen.c (revision d9306527b4a7229dcf0cf3c58aed36bb9da82854)
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  */
freopen(const char * name,const char * mode,FILE * f)15 FILE *freopen(const char *name, const char *mode, FILE *f){
16 	int m;
17 
18 	if(f->state!=CLOSED){
19 		fclose(f);
20 /* premature; fall through and see what happens */
21 /*		f->state=OPEN; */
22 	}
23 
24 	m = *mode++;
25 	if(m == 0)
26 		return NULL;
27 	if(*mode == 'b')
28 		mode++;
29 	switch(m){
30 	default:
31 		return NULL;
32 	case 'r':
33 		f->fd=open(name, (*mode == '+'? ORDWR: OREAD));
34 		break;
35 	case 'w':
36 		f->fd=create(name, (*mode == '+'? ORDWR: OWRITE), 0666);
37 		break;
38 	case 'a':
39 		m = (*mode == '+'? ORDWR: OWRITE);
40 		f->fd=open(name, m);
41 		if(f->fd<0)
42 			f->fd=create(name, m, 0666);
43 		seek(f->fd, 0LL, 2);
44 		break;
45 	}
46 
47 	if(f->fd==-1)
48 		return NULL;
49 	f->flags=(mode[0]=='a')? APPEND : 0;
50 	f->state=OPEN;
51 	f->buf=0;
52 	f->rp=0;
53 	f->wp=0;
54 	f->lp=0;
55 	return f;
56 }
57