xref: /titanic_50/usr/src/lib/libbc/libc/stdio/4.2/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 /*
23  * Copyright 1986 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*      Copyright (c) 1984 AT&T */
28 /*        All Rights Reserved   */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"  /* from S5R2 1.8 */
31 
32 /*LINTLIBRARY*/
33 #include <stdio.h>
34 #include <fcntl.h>
35 
36 extern int open(), fclose();
37 extern FILE *_findiop(), *_endopen();
38 
39 FILE *
40 fopen(file, mode)
41 char	*file, *mode;
42 {
43 	return (_endopen(file, mode, _findiop()));
44 }
45 
46 FILE *
47 freopen(file, mode, iop)
48 char	*file, *mode;
49 register FILE *iop;
50 {
51 	(void) fclose(iop); /* doesn't matter if this fails */
52 	return (_endopen(file, mode, iop));
53 }
54 
55 static FILE *
56 _endopen(file, mode, iop)
57 char	*file, *mode;
58 register FILE *iop;
59 {
60 	register int	plus, oflag, fd;
61 
62 	if (iop == NULL || file == NULL || file[0] == '\0')
63 		return (NULL);
64 	plus = (mode[1] == '+');
65 	switch (mode[0]) {
66 	case 'w':
67 		oflag = (plus ? O_RDWR : O_WRONLY) | O_TRUNC | O_CREAT;
68 		break;
69 	case 'a':
70 		oflag = (plus ? O_RDWR : O_WRONLY) | O_CREAT;
71 		break;
72 	case 'r':
73 		oflag = plus ? O_RDWR : O_RDONLY;
74 		break;
75 	default:
76 		return (NULL);
77 	}
78 	if ((fd = open(file, oflag, 0666)) < 0)
79 		return (NULL);
80 	iop->_cnt = 0;
81 	iop->_file = fd;
82 	iop->_flag = plus ? _IORW : (mode[0] == 'r') ? _IOREAD : _IOWRT;
83 	if (mode[0] == 'a')   {
84 		if ((lseek(fd,0L,2)) < 0)  {
85 			(void) close(fd);
86 			return NULL;
87 		}
88 	}
89 	iop->_base = iop->_ptr = NULL;
90 	iop->_bufsiz = 0;
91 	return (iop);
92 }
93