xref: /titanic_52/usr/src/lib/libc/port/stdio/fgets.c (revision 06e46062ef4f5f4b687cbafb4518fb123fe23920)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*	Copyright (c) 1988 AT&T	*/
30 /*	  All Rights Reserved  	*/
31 
32 
33 #include "synonyms.h"
34 #include "file64.h"
35 #include "mtlib.h"
36 #include <stdio.h>
37 #include <memory.h>
38 #include <errno.h>
39 #include <thread.h>
40 #include <synch.h>
41 #include <sys/types.h>
42 #include "stdiom.h"
43 #include "mse.h"
44 
45 /* read size-max line from stream, including '\n' */
46 char *
47 fgets(char *buf, int size, FILE *iop)
48 {
49 	char *ptr = buf;
50 	int n;
51 	Uchar *bufend;
52 	char *p;
53 	rmutex_t *lk;
54 
55 	FLOCKFILE(lk, iop);
56 
57 	_SET_ORIENTATION_BYTE(iop);
58 
59 	if (!(iop->_flag & (_IOREAD | _IORW))) {
60 		errno = EBADF;
61 		FUNLOCKFILE(lk);
62 		return (NULL);
63 	}
64 
65 	if (iop->_base == NULL) {
66 		if ((bufend = _findbuf(iop)) == NULL) {
67 			FUNLOCKFILE(lk);
68 			return (NULL);
69 		}
70 	}
71 	else
72 		bufend = _bufend(iop);
73 
74 	size--;		/* room for '\0' */
75 	while (size > 0) {
76 		/* empty buffer */
77 		if (iop->_cnt <= 0) {
78 			if (__filbuf(iop) != EOF) {
79 				iop->_ptr--;	/* put back the character */
80 				iop->_cnt++;
81 			} else if (ptr == buf) {  /* never read anything */
82 				FUNLOCKFILE(lk);
83 				return (NULL);
84 			} else
85 				break;		/* nothing left to read */
86 		}
87 		n = (int)(size < iop->_cnt ? size : iop->_cnt);
88 		if ((p = memccpy(ptr, (char *)iop->_ptr, '\n',
89 		    (size_t)n)) != NULL)
90 			n = (int)(p - ptr);
91 		ptr += n;
92 		iop->_cnt -= n;
93 		iop->_ptr += n;
94 		if (_needsync(iop, bufend))
95 			_bufsync(iop, bufend);
96 		if (p != NULL)
97 			break; /* newline found */
98 		size -= n;
99 	}
100 	FUNLOCKFILE(lk);
101 	*ptr = '\0';
102 	return (buf);
103 }
104