xref: /illumos-gate/usr/src/cmd/ipf/lib/getline.c (revision fb876f9607a4e506a871e6b539d75c9644a3566f)
1 /*
2  * Copyright (C) 1993-2001 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * $Id: getline.c,v 1.3 2001/06/09 17:09:24 darrenr Exp $
7  */
8 
9 #include <stdio.h>
10 #if !defined(__SVR4) && !defined(__GNUC__)
11 #include <strings.h>
12 #endif
13 #include <string.h>
14 #include "ipf.h"
15 
16 
17 /*
18  * Similar to fgets(3) but can handle '\\' and NL is converted to NUL.
19  * Returns NULL if error occured, EOF encounterd or input line is too long.
20  */
21 char *
22 getaline(char *str, size_t size, FILE *file, int *linenum)
23 {
24 	char *p;
25 	int s, len;
26 
27 	do {
28 		for (p = str, s = size; ; p += (len - 1), s -= (len - 1)) {
29 			/*
30 			 * if an error occured, EOF was encounterd, or there
31 			 * was no room to put NUL, return NULL.
32 			 */
33 			if (fgets(p, s, file) == NULL)
34 				return (NULL);
35 			len = strlen(p);
36 			if (p[len - 1] != '\n') {
37 				p[len] = '\0';
38 				break;
39 			}
40 			(*linenum)++;
41 			p[len - 1] = '\0';
42 			if (len < 2 || p[len - 2] != '\\')
43 				break;
44 			else
45 				/*
46 				 * Convert '\\' to a space so words don't
47 				 * run together
48 				 */
49 				p[len - 2] = ' ';
50 		}
51 	} while (*str == '\0');
52 	return (str);
53 }
54