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#pragma ident	"%Z%%M%	%I%	%E% SMI"
31
32#include "lint.h"
33#include "file64.h"
34#include "mtlib.h"
35#include <stdio.h>
36#include <memory.h>
37#include <errno.h>
38#include <thread.h>
39#include <synch.h>
40#include <sys/types.h>
41#include "stdiom.h"
42#include "mse.h"
43
44/* read size-max line from stream, including '\n' */
45char *
46fgets(char *buf, int size, FILE *iop)
47{
48	char *ptr = buf;
49	int n;
50	Uchar *bufend;
51	char *p;
52	rmutex_t *lk;
53
54	FLOCKFILE(lk, iop);
55
56	_SET_ORIENTATION_BYTE(iop);
57
58	if (!(iop->_flag & (_IOREAD | _IORW))) {
59		errno = EBADF;
60		FUNLOCKFILE(lk);
61		return (NULL);
62	}
63
64	if (iop->_base == NULL) {
65		if ((bufend = _findbuf(iop)) == NULL) {
66			FUNLOCKFILE(lk);
67			return (NULL);
68		}
69	}
70	else
71		bufend = _bufend(iop);
72
73	size--;		/* room for '\0' */
74	while (size > 0) {
75		/* empty buffer */
76		if (iop->_cnt <= 0) {
77			if (__filbuf(iop) != EOF) {
78				iop->_ptr--;	/* put back the character */
79				iop->_cnt++;
80			} else if (ptr == buf) {  /* never read anything */
81				FUNLOCKFILE(lk);
82				return (NULL);
83			} else
84				break;		/* nothing left to read */
85		}
86		n = (int)(size < iop->_cnt ? size : iop->_cnt);
87		if ((p = memccpy(ptr, (char *)iop->_ptr, '\n',
88		    (size_t)n)) != NULL)
89			n = (int)(p - ptr);
90		ptr += n;
91		iop->_cnt -= n;
92		iop->_ptr += n;
93		if (_needsync(iop, bufend))
94			_bufsync(iop, bufend);
95		if (p != NULL)
96			break; /* newline found */
97		size -= n;
98	}
99	FUNLOCKFILE(lk);
100	*ptr = '\0';
101	return (buf);
102}
103