xref: /csrg-svn/lib/libc/stdio/fopen.c (revision 61180)
146079Sbostic /*-
2*61180Sbostic  * Copyright (c) 1990, 1993
3*61180Sbostic  *	The Regents of the University of California.  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*61180Sbostic static char sccsid[] = "@(#)fopen.c	8.1 (Berkeley) 06/04/93";
1346079Sbostic #endif /* LIBC_SCCS and not lint */
1421404Sdist 
1517951Sserge #include <sys/types.h>
1646079Sbostic #include <sys/stat.h>
1746278Storek #include <fcntl.h>
1817951Sserge #include <stdio.h>
1946079Sbostic #include <errno.h>
2046079Sbostic #include "local.h"
212004Swnj 
222004Swnj FILE *
fopen(file,mode)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;
4646278Storek 
4746278Storek 	/*
4846278Storek 	 * When opening in append mode, even though we use O_APPEND,
4946278Storek 	 * we need to seek to the end so that ftell() gets the right
5046278Storek 	 * answer.  If the user then alters the seek pointer, or
5146278Storek 	 * the file extends, this will fail, but there is not much
5246278Storek 	 * we can do about this.  (We could set __SAPP and check in
5346278Storek 	 * fseek and ftell.)
5446278Storek 	 */
5546278Storek 	if (oflags & O_APPEND)
5646278Storek 		(void) __sseek((void *)fp, (fpos_t)0, SEEK_END);
5746079Sbostic 	return (fp);
582004Swnj }
59