1 /* @(#)filewrite.c	1.18 12/02/26 Copyright 1986, 1995-2012 J. Schilling */
2 /*
3  *	Copyright (c) 1986, 1995-2012 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  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file CDDL.Schily.txt from this distribution.
15  */
16 
17 #include "schilyio.h"
18 
19 static	char	_writeerr[]	= "file_write_err";
20 
21 #ifdef	HAVE_USG_STDIO
22 
23 EXPORT ssize_t
24 filewrite(f, vbuf, len)
25 	register FILE	*f;
26 	void	*vbuf;
27 	size_t	len;
28 {
29 	register int	n;
30 	ssize_t	cnt;
31 	char	*buf = vbuf;
32 
33 	down2(f, _IOWRT, _IORW);
34 
35 	if (f->_flag & _IONBF) {
36 		cnt = _niwrite(fileno(f), buf, len);
37 		if (cnt < 0) {
38 			f->_flag |= _IOERR;
39 			if (!(my_flag(f) & _JS_IONORAISE))
40 				raisecond(_writeerr, 0L);
41 		}
42 		return (cnt);
43 	}
44 	cnt = 0;
45 	while (len > 0) {
46 		if (f->_cnt <= 0) {
47 			if (usg_flsbuf((unsigned char) *buf++, f) == EOF)
48 				break;
49 			cnt++;
50 			if (--len == 0)
51 				break;
52 		}
53 		if ((n = f->_cnt >= len ? len : f->_cnt) > 0) {
54 			f->_ptr = (unsigned char *)movebytes(buf, f->_ptr, n);
55 			buf += n;
56 			f->_cnt -= n;
57 			cnt += n;
58 			len -= n;
59 		}
60 	}
61 	if (!ferror(f))
62 		return (cnt);
63 	if (!(my_flag(f) & _JS_IONORAISE) && !(_io_glflag & _JS_IONORAISE))
64 		raisecond(_writeerr, 0L);
65 	return (-1);
66 }
67 
68 #else
69 
70 EXPORT ssize_t
71 filewrite(f, vbuf, len)
72 	register FILE	*f;
73 	void	*vbuf;
74 	size_t	len;
75 {
76 	ssize_t	cnt;
77 	char	*buf = vbuf;
78 
79 	down2(f, _IOWRT, _IORW);
80 
81 	if (my_flag(f) & _JS_IOUNBUF)
82 		return (_niwrite(fileno(f), buf, len));
83 	cnt = fwrite(buf, 1, len, f);
84 
85 	if (!ferror(f))
86 		return (cnt);
87 	if (!(my_flag(f) & _JS_IONORAISE) && !(_io_glflag & _JS_IONORAISE))
88 		raisecond(_writeerr, 0L);
89 	return (-1);
90 }
91 
92 #endif	/* HAVE_USG_STDIO */
93