1 /* @(#)fileread.c	1.17 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  * 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 static	char	_readerr[]	= "file_read_err";
22 
23 #ifdef	HAVE_USG_STDIO
24 
25 EXPORT ssize_t
fileread(f,buf,len)26 fileread(f, buf, len)
27 	register FILE	*f;
28 	void	*buf;
29 	size_t	len;
30 {
31 	ssize_t	cnt;
32 	register int	n;
33 
34 	down2(f, _IOREAD, _IORW);
35 
36 	if (f->_flag & _IONBF) {
37 		cnt = _niread(fileno(f), buf, len);
38 		if (cnt < 0) {
39 			f->_flag |= _IOERR;
40 			if (!(my_flag(f) & _JS_IONORAISE))
41 				raisecond(_readerr, 0L);
42 		}
43 		if (cnt == 0 && len)
44 			f->_flag |= _IOEOF;
45 		return (cnt);
46 	}
47 	cnt = 0;
48 	while (len > 0) {
49 		if (f->_cnt <= 0) {
50 			if (usg_filbuf(f) == EOF)
51 				break;
52 			f->_cnt++;
53 			f->_ptr--;
54 		}
55 		n = f->_cnt >= len ? len : f->_cnt;
56 		buf = (void *)movebytes(f->_ptr, buf, n);
57 		f->_ptr += n;
58 		f->_cnt -= n;
59 		cnt += n;
60 		len -= n;
61 	}
62 	if (!ferror(f))
63 		return (cnt);
64 	if (!(my_flag(f) & _JS_IONORAISE) && !(_io_glflag & _JS_IONORAISE))
65 		raisecond(_readerr, 0L);
66 	return (-1);
67 }
68 
69 #else
70 
71 EXPORT ssize_t
fileread(f,buf,len)72 fileread(f, buf, len)
73 	register FILE	*f;
74 	void	*buf;
75 	size_t	len;
76 {
77 	ssize_t	cnt;
78 
79 	down2(f, _IOREAD, _IORW);
80 
81 	if (my_flag(f) & _JS_IOUNBUF)
82 		return (_niread(fileno(f), buf, len));
83 	cnt = fread(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(_readerr, 0L);
89 	return (-1);
90 }
91 
92 #endif	/* HAVE_USG_STDIO */
93