summaryrefslogtreecommitdiff
path: root/usr/src/lib/libc/port/stdio/fgets.c
blob: 972223d4fff613fa28a4c0d56b103b2740b30a98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*	Copyright (c) 1988 AT&T	*/
/*	  All Rights Reserved  	*/


#include "synonyms.h"
#include "file64.h"
#include "mtlib.h"
#include <stdio.h>
#include <memory.h>
#include <errno.h>
#include <thread.h>
#include <synch.h>
#include <sys/types.h>
#include "stdiom.h"
#include "mse.h"

/* read size-max line from stream, including '\n' */
char *
fgets(char *buf, int size, FILE *iop)
{
	char *ptr = buf;
	int n;
	Uchar *bufend;
	char *p;
	rmutex_t *lk;

	FLOCKFILE(lk, iop);

	_SET_ORIENTATION_BYTE(iop);

	if (!(iop->_flag & (_IOREAD | _IORW))) {
		errno = EBADF;
		FUNLOCKFILE(lk);
		return (NULL);
	}

	if (iop->_base == NULL) {
		if ((bufend = _findbuf(iop)) == NULL) {
			FUNLOCKFILE(lk);
			return (NULL);
		}
	}
	else
		bufend = _bufend(iop);

	size--;		/* room for '\0' */
	while (size > 0) {
		/* empty buffer */
		if (iop->_cnt <= 0) {
			if (__filbuf(iop) != EOF) {
				iop->_ptr--;	/* put back the character */
				iop->_cnt++;
			} else if (ptr == buf) {  /* never read anything */
				FUNLOCKFILE(lk);
				return (NULL);
			} else
				break;		/* nothing left to read */
		}
		n = (int)(size < iop->_cnt ? size : iop->_cnt);
		if ((p = memccpy(ptr, (char *)iop->_ptr, '\n',
		    (size_t)n)) != NULL)
			n = (int)(p - ptr);
		ptr += n;
		iop->_cnt -= n;
		iop->_ptr += n;
		if (_needsync(iop, bufend))
			_bufsync(iop, bufend);
		if (p != NULL)
			break; /* newline found */
		size -= n;
	}
	FUNLOCKFILE(lk);
	*ptr = '\0';
	return (buf);
}