xref: /original-bsd/lib/libc/stdio/freopen.c (revision 6c57d260)
1 /* @(#)freopen.c	4.2 (Berkeley) 03/09/81 */
2 #include	<stdio.h>
3 #include	<errno.h>
4 
5 FILE *
6 freopen(file, mode, iop)
7 char *file;
8 register char *mode;
9 register FILE *iop;
10 {
11 	extern int errno;
12 	register f, rw;
13 
14 	rw = mode[1] == '+';
15 
16 	fclose(iop);
17 	if (*mode=='w') {
18 		f = creat(file, 0666);
19 		if (rw && f>=0) {
20 			close(f);
21 			f = open(file, 2);
22 		}
23 	} else if (*mode=='a') {
24 		if ((f = open(file, rw? 2: 1)) < 0) {
25 			if (errno == ENOENT) {
26 				f = creat(file, 0666);
27 				if (rw && f>=0) {
28 					close(f);
29 					f = open(file, 2);
30 				}
31 			}
32 		}
33 		if (f >= 0)
34 			lseek(f, 0L, 2);
35 	} else
36 		f = open(file, rw? 2: 0);
37 	if (f < 0)
38 		return(NULL);
39 	iop->_cnt = 0;
40 	iop->_file = f;
41 	if (rw)
42 		iop->_flag |= _IORW;
43 	else if (*mode != 'r')
44 		iop->_flag |= _IOWRT;
45 	else
46 		iop->_flag |= _IOREAD;
47 	return(iop);
48 }
49