xref: /titanic_50/usr/src/lib/libbc/libc/stdio/4.2/fopen.c (revision 7c1d35456b77b833f089b886b99aa431a24e1377)
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"
31 
32 /*LINTLIBRARY*/
33 #include <stdio.h>
34 #include <fcntl.h>
35 
36 extern int	fclose();
37 extern FILE	*_findiop();
38 
39 static FILE	*_endopen(char *, char *, FILE *);
40 
41 FILE *
42 fopen(char *file, char *mode)
43 {
44 	return (_endopen(file, mode, _findiop()));
45 }
46 
47 FILE *
48 freopen(char *file, char *mode, FILE *iop)
49 {
50 	(void) fclose(iop); /* doesn't matter if this fails */
51 	return (_endopen(file, mode, iop));
52 }
53 
54 static FILE *
55 _endopen(char *file, char *mode, FILE *iop)
56 {
57 	int	plus, oflag, fd;
58 
59 	if (iop == NULL || file == NULL || file[0] == '\0')
60 		return (NULL);
61 	plus = (mode[1] == '+');
62 	switch (mode[0]) {
63 	case 'w':
64 		oflag = (plus ? O_RDWR : O_WRONLY) | O_TRUNC | O_CREAT;
65 		break;
66 	case 'a':
67 		oflag = (plus ? O_RDWR : O_WRONLY) | O_CREAT;
68 		break;
69 	case 'r':
70 		oflag = plus ? O_RDWR : O_RDONLY;
71 		break;
72 	default:
73 		return (NULL);
74 	}
75 	if ((fd = open(file, oflag, 0666)) < 0)
76 		return (NULL);
77 	iop->_cnt = 0;
78 	iop->_file = fd;
79 	iop->_flag = plus ? _IORW : (mode[0] == 'r') ? _IOREAD : _IOWRT;
80 	if (mode[0] == 'a')   {
81 		if ((lseek(fd,0L,2)) < 0)  {
82 			(void) close(fd);
83 			return NULL;
84 		}
85 	}
86 	iop->_base = iop->_ptr = NULL;
87 	iop->_bufsiz = 0;
88 	return (iop);
89 }
90