/*
 * Copyright (c) 2004, 2005 Sendmail, Inc. and its suppliers.
 *      All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: fgetline0.c,v 1.6 2006/07/14 14:42:25 ca Exp $")
#include "sm/error.h"
#include "sm/io.h"
#include "sm/assert.h"
#include "sm/memops.h"
#include "sm/str.h"
#include "io-int.h"

/*
**  SM_FGETLINE0 -- get a line from a file; the end of the line when read is
**	\r\n, however, those characters are not in str; but str is terminated
**	(trailing '\0' is not counted for length of str)
**
**	Parameters:
**		fp -- file pointer to read from
**		str -- str to place read data
**
**	Returns:
**		usual sm_error code
*/

sm_ret_T
sm_fgetline0(sm_file_T *fp, sm_str_P str)
{
	int ch;
	sm_ret_T ret;

	SM_IS_FP(fp);

	while ((ch = sm_getc(fp)) != SM_IO_EOF && !sm_is_err(ch))
	{
		while (ch == '\r')
		{
			ch = sm_getc(fp);
			if (ch == '\n')
				return sm_str_term(str);
			if (ch == SM_IO_EOF || sm_is_err(ch))
				return ch;

			/* not \r\n, hence put back \r, ch done below */
			ret = sm_str_put(str, (uchar) '\r');
			if (sm_is_err(ret))
				return ret;
		}
		ret = sm_str_put(str, (uchar) ch);
		if (sm_is_err(ret))
			return ret;
	}
	return ch;
}


syntax highlighted by Code2HTML, v. 0.9.1