1 /* @(#)fcons.c	2.20 10/11/06 Copyright 1986, 1995-2010 J. Schilling */
2 /*
3  *	Copyright (c) 1986, 1995-2010  J. Schilling
4  */
5 /*
6  * The contents of this file are subject to the terms of the
7  * Common Development and Distribution License, Version 1.0 only
8  * (the "License").  You may not use this file except in compliance
9  * with the License.
10  *
11  * See the file CDDL.Schily.txt in this distribution for details.
12  * A copy of the CDDL is also available via the Internet at
13  * http://www.opensource.org/licenses/cddl1.txt
14  *
15  * When distributing Covered Code, include this CDDL HEADER in each
16  * file and include the License file CDDL.Schily.txt from this distribution.
17  */
18 
19 #include "schilyio.h"
20 
21 /*
22  * Note that because of a definition in schilyio.h we are using
23  * fseeko()/ftello() instead of fseek()/ftell() if available.
24  */
25 
26 LOCAL	char	*fmtab[] = {
27 			"",	/* 0	FI_NONE				*/
28 			"r",	/* 1	FI_READ				*/
29 			"w",	/* 2	FI_WRITE		**1)	*/
30 			"r+",	/* 3	FI_READ  | FI_WRITE		*/
31 			"b",	/* 4	FI_NONE  | FI_BINARY		*/
32 			"rb",	/* 5	FI_READ  | FI_BINARY		*/
33 			"wb",	/* 6	FI_WRITE | FI_BINARY	**1)	*/
34 			"r+b",	/* 7	FI_READ  | FI_WRITE | FI_BINARY	*/
35 
36 /* + FI_APPEND	*/	"",	/* 0	FI_NONE				*/
37 /* ...		*/	"r",	/* 1	FI_READ				*/
38 			"a",	/* 2	FI_WRITE		**1)	*/
39 			"a+",	/* 3	FI_READ  | FI_WRITE		*/
40 			"b",	/* 4	FI_NONE  | FI_BINARY		*/
41 			"rb",	/* 5	FI_READ  | FI_BINARY		*/
42 			"ab",	/* 6	FI_WRITE | FI_BINARY	**1)	*/
43 			"a+b",	/* 7	FI_READ  | FI_WRITE | FI_BINARY	*/
44 		};
45 /*
46  * NOTES:
47  *	1)	fdopen() guarantees not to create/trunc files in this case
48  *
49  *	"w"	will create/trunc files with fopen()
50  *	"a"	will create files with fopen()
51  */
52 
53 
54 EXPORT FILE *
_fcons(fd,f,flag)55 _fcons(fd, f, flag)
56 	register FILE	*fd;
57 		int	f;
58 		int	flag;
59 {
60 	int	my_gflag = _io_glflag;
61 
62 	if (fd == (FILE *)NULL)
63 		fd = fdopen(f,
64 			fmtab[flag&(FI_READ|FI_WRITE|FI_BINARY | FI_APPEND)]);
65 
66 	if (fd != (FILE *)NULL) {
67 		if (flag & FI_APPEND) {
68 			(void) fseek(fd, (off_t)0, SEEK_END);
69 		}
70 		if (flag & FI_UNBUF) {
71 			setbuf(fd, NULL);
72 			my_gflag |= _JS_IOUNBUF;
73 		}
74 		set_my_flag(fd, my_gflag); /* must clear it if fd is reused */
75 		return (fd);
76 	}
77 	if (flag & FI_CLOSE)
78 		close(f);
79 
80 	return ((FILE *)NULL);
81 }
82