xref: /titanic_52/usr/src/lib/libbc/libc/stdio/sys5/fopen.c (revision 84ab085a13f931bc78e7415e7ce921dbaa14fcb3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*      Copyright (c) 1984 AT&T */
23 /*        All Rights Reserved   */
24 
25 #pragma ident	"%Z%%M%	%I%	%E% SMI"  /* from S5R2 1.8 */
26 
27 /*LINTLIBRARY*/
28 #include <stdio.h>
29 #include <fcntl.h>
30 
31 extern int open(), fclose();
32 extern FILE *_findiop(), *_endopen();
33 
34 FILE *
35 fopen(file, mode)
36 char	*file, *mode;
37 {
38 	return (_endopen(file, mode, _findiop()));
39 }
40 
41 FILE *
42 freopen(file, mode, iop)
43 char	*file, *mode;
44 register FILE *iop;
45 {
46 	(void) fclose(iop); /* doesn't matter if this fails */
47 	return (_endopen(file, mode, iop));
48 }
49 
50 static FILE *
51 _endopen(file, mode, iop)
52 char	*file, *mode;
53 register FILE *iop;
54 {
55 	register int	plus, oflag, fd;
56 
57 	if (iop == NULL || file == NULL || file[0] == '\0')
58 		return (NULL);
59 	plus = (mode[1] == '+');
60 	switch (mode[0]) {
61 	case 'w':
62 		oflag = (plus ? O_RDWR : O_WRONLY) | O_TRUNC | O_CREAT;
63 		break;
64 	case 'a':
65 		oflag = (plus ? O_RDWR : O_WRONLY) | O_APPEND | O_CREAT;
66 		break;
67 	case 'r':
68 		oflag = plus ? O_RDWR : O_RDONLY;
69 		break;
70 	default:
71 		return (NULL);
72 	}
73 	if ((fd = open(file, oflag, 0666)) < 0)
74 		return (NULL);
75 	iop->_cnt = 0;
76 	iop->_file = fd;
77 	iop->_flag = plus ? _IORW : (mode[0] == 'r') ? _IOREAD : _IOWRT;
78 	if (mode[0] == 'a')   {
79 		if (!plus)  {
80 			/* if update only mode, move file pointer to the end
81 			   of the file */
82 			if ((lseek(fd,0L,2)) < 0)  {
83 				(void) close(fd);
84 				return NULL;
85 			}
86 		}
87 	}
88 	iop->_base = iop->_ptr = NULL;
89 	iop->_bufsiz = 0;
90 	return (iop);
91 }
92