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