BSD 3 development
[unix-history] / .ref-BSD-2 / src / libNS / fopen.c
CommitLineData
d0391c55
KS
1/* Copyright (c) 1979 Regents of the University of California */
2#include <stdio.h>
3
4struct _iobuf *fopen(file, mode)
5register char *mode;
6{
7 register f;
8 register struct _iobuf *iop;
9 int unixmode, a_flag;
10
11 for (iop = _iob; iop->_flag&(_IOREAD|_IOWRT); iop++)
12 if (iop >= _iob + _NFILE)
13 return(NULL);
14 iop->_flag = 0;
15 iop->_delta = 0;
16 a_flag = 0;
17 for(;*mode;mode++) {
18 switch(*mode) {
19
20 case 'w':
21 iop->_flag |= _IOWRT;
22 break;
23
24 case 'r':
25 iop->_flag |= _IOREAD;
26 break;
27
28 case 'a':
29 a_flag = 1;
30 iop->_flag |= _IOWRT ;
31 }
32 }
33 if((unixmode = (iop->_flag & 3) - 1) < 0) {
34 unixmode = 0;
35 iop->_flag = 1;
36 }
37 if ((iop->_flag & _IOWRT) && a_flag==0 ) {
38 f = creat(file, 0644);
39 if((iop->_flag & _IOREAD) && (f>0)) {
40 close(f);
41 f = open(file,2);
42 }
43 }
44 else
45 if ((0 >(f = open(file, unixmode))) && (a_flag || !(iop->_flag&_IOREAD))) {
46 f = creat(file, 0644);
47 close(f);
48 f = open(file,unixmode);
49 }
50
51 if (f < 0)
52 return(NULL);
53 if (a_flag)
54 lseek(f, (long) 0, 2);
55 iop->_file = f;
56 return(iop);
57}