xref: /titanic_51/usr/src/cmd/ipf/lib/common/getline.c (revision 23a1ccea6aac035f084a7a4cdc968687d1b02daf)
17c478bd9Sstevel@tonic-gate /*
27c478bd9Sstevel@tonic-gate  * Copyright (C) 1993-2001 by Darren Reed.
37c478bd9Sstevel@tonic-gate  *
47c478bd9Sstevel@tonic-gate  * See the IPFILTER.LICENCE file for details on licencing.
57c478bd9Sstevel@tonic-gate  *
67c478bd9Sstevel@tonic-gate  * $Id: getline.c,v 1.3 2001/06/09 17:09:24 darrenr Exp $
77c478bd9Sstevel@tonic-gate  */
87c478bd9Sstevel@tonic-gate 
97c478bd9Sstevel@tonic-gate #include <stdio.h>
107c478bd9Sstevel@tonic-gate #if !defined(__SVR4) && !defined(__GNUC__)
117c478bd9Sstevel@tonic-gate #include <strings.h>
127c478bd9Sstevel@tonic-gate #endif
137c478bd9Sstevel@tonic-gate #include <string.h>
147c478bd9Sstevel@tonic-gate #include "ipf.h"
157c478bd9Sstevel@tonic-gate 
167c478bd9Sstevel@tonic-gate 
177c478bd9Sstevel@tonic-gate /*
187c478bd9Sstevel@tonic-gate  * Similar to fgets(3) but can handle '\\' and NL is converted to NUL.
197c478bd9Sstevel@tonic-gate  * Returns NULL if error occured, EOF encounterd or input line is too long.
207c478bd9Sstevel@tonic-gate  */
21*23a1cceaSRoger A. Faulkner char *
22*23a1cceaSRoger A. Faulkner getaline(char *str, size_t size, FILE *file, int *linenum)
237c478bd9Sstevel@tonic-gate {
247c478bd9Sstevel@tonic-gate 	char *p;
257c478bd9Sstevel@tonic-gate 	int s, len;
267c478bd9Sstevel@tonic-gate 
277c478bd9Sstevel@tonic-gate 	do {
287c478bd9Sstevel@tonic-gate 		for (p = str, s = size; ; p += (len - 1), s -= (len - 1)) {
297c478bd9Sstevel@tonic-gate 			/*
307c478bd9Sstevel@tonic-gate 			 * if an error occured, EOF was encounterd, or there
317c478bd9Sstevel@tonic-gate 			 * was no room to put NUL, return NULL.
327c478bd9Sstevel@tonic-gate 			 */
337c478bd9Sstevel@tonic-gate 			if (fgets(p, s, file) == NULL)
347c478bd9Sstevel@tonic-gate 				return (NULL);
357c478bd9Sstevel@tonic-gate 			len = strlen(p);
367c478bd9Sstevel@tonic-gate 			if (p[len - 1] != '\n') {
377c478bd9Sstevel@tonic-gate 				p[len] = '\0';
387c478bd9Sstevel@tonic-gate 				break;
397c478bd9Sstevel@tonic-gate 			}
407c478bd9Sstevel@tonic-gate 			(*linenum)++;
417c478bd9Sstevel@tonic-gate 			p[len - 1] = '\0';
427c478bd9Sstevel@tonic-gate 			if (len < 2 || p[len - 2] != '\\')
437c478bd9Sstevel@tonic-gate 				break;
447c478bd9Sstevel@tonic-gate 			else
457c478bd9Sstevel@tonic-gate 				/*
467c478bd9Sstevel@tonic-gate 				 * Convert '\\' to a space so words don't
477c478bd9Sstevel@tonic-gate 				 * run together
487c478bd9Sstevel@tonic-gate 				 */
497c478bd9Sstevel@tonic-gate 				p[len - 2] = ' ';
507c478bd9Sstevel@tonic-gate 		}
517c478bd9Sstevel@tonic-gate 	} while (*str == '\0');
527c478bd9Sstevel@tonic-gate 	return (str);
537c478bd9Sstevel@tonic-gate }
54