xref: /original-bsd/lib/libc/stdio/fopen.c (revision c3e32dec)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)fopen.c	8.1 (Berkeley) 06/04/93";
13 #endif /* LIBC_SCCS and not lint */
14 
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <errno.h>
20 #include "local.h"
21 
22 FILE *
23 fopen(file, mode)
24 	const char *file;
25 	const char *mode;
26 {
27 	register FILE *fp;
28 	register int f;
29 	int flags, oflags;
30 
31 	if ((flags = __sflags(mode, &oflags)) == 0)
32 		return (NULL);
33 	if ((fp = __sfp()) == NULL)
34 		return (NULL);
35 	if ((f = open(file, oflags, DEFFILEMODE)) < 0) {
36 		fp->_flags = 0;			/* release */
37 		return (NULL);
38 	}
39 	fp->_file = f;
40 	fp->_flags = flags;
41 	fp->_cookie = fp;
42 	fp->_read = __sread;
43 	fp->_write = __swrite;
44 	fp->_seek = __sseek;
45 	fp->_close = __sclose;
46 
47 	/*
48 	 * When opening in append mode, even though we use O_APPEND,
49 	 * we need to seek to the end so that ftell() gets the right
50 	 * answer.  If the user then alters the seek pointer, or
51 	 * the file extends, this will fail, but there is not much
52 	 * we can do about this.  (We could set __SAPP and check in
53 	 * fseek and ftell.)
54 	 */
55 	if (oflags & O_APPEND)
56 		(void) __sseek((void *)fp, (fpos_t)0, SEEK_END);
57 	return (fp);
58 }
59