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