xref: /csrg-svn/lib/libc/stdio/fopen.c (revision 46278)
146079Sbostic /*-
246079Sbostic  * Copyright (c) 1990 The Regents of the University of California.
346079Sbostic  * All rights reserved.
446079Sbostic  *
546079Sbostic  * This code is derived from software contributed to Berkeley by
646079Sbostic  * Chris Torek.
746079Sbostic  *
846079Sbostic  * %sccs.include.redist.c%
921404Sdist  */
1021404Sdist 
1126647Sdonn #if defined(LIBC_SCCS) && !defined(lint)
12*46278Storek static char sccsid[] = "@(#)fopen.c	5.5 (Berkeley) 02/05/91";
1346079Sbostic #endif /* LIBC_SCCS and not lint */
1421404Sdist 
1517951Sserge #include <sys/types.h>
1646079Sbostic #include <sys/stat.h>
17*46278Storek #include <fcntl.h>
1817951Sserge #include <stdio.h>
1946079Sbostic #include <errno.h>
2046079Sbostic #include "local.h"
212004Swnj 
222004Swnj FILE *
232004Swnj fopen(file, mode)
2446271Storek 	const char *file;
2546271Storek 	const char *mode;
262004Swnj {
2746079Sbostic 	register FILE *fp;
2846079Sbostic 	register int f;
2946079Sbostic 	int flags, oflags;
302004Swnj 
3146079Sbostic 	if ((flags = __sflags(mode, &oflags)) == 0)
3217951Sserge 		return (NULL);
3346079Sbostic 	if ((fp = __sfp()) == NULL)
3417951Sserge 		return (NULL);
3546079Sbostic 	if ((f = open(file, oflags, DEFFILEMODE)) < 0) {
3646079Sbostic 		fp->_flags = 0;			/* release */
3746079Sbostic 		return (NULL);
3817951Sserge 	}
3946079Sbostic 	fp->_file = f;
4046079Sbostic 	fp->_flags = flags;
4146079Sbostic 	fp->_cookie = fp;
4246079Sbostic 	fp->_read = __sread;
4346079Sbostic 	fp->_write = __swrite;
4446079Sbostic 	fp->_seek = __sseek;
4546079Sbostic 	fp->_close = __sclose;
46*46278Storek 
47*46278Storek 	/*
48*46278Storek 	 * When opening in append mode, even though we use O_APPEND,
49*46278Storek 	 * we need to seek to the end so that ftell() gets the right
50*46278Storek 	 * answer.  If the user then alters the seek pointer, or
51*46278Storek 	 * the file extends, this will fail, but there is not much
52*46278Storek 	 * we can do about this.  (We could set __SAPP and check in
53*46278Storek 	 * fseek and ftell.)
54*46278Storek 	 */
55*46278Storek 	if (oflags & O_APPEND)
56*46278Storek 		(void) __sseek((void *)fp, (fpos_t)0, SEEK_END);
5746079Sbostic 	return (fp);
582004Swnj }
59