-
Notifications
You must be signed in to change notification settings - Fork 0
/
readline.c
77 lines (67 loc) · 1.29 KB
/
readline.c
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
/* readline.c
* Ralf Becker
* Institut fuer Thermische Stroemungsmaschinen
* Universitaet Karlsruhe
* 2002
* $Id: readline.c,v 1.2.2.3 2006/04/25 20:04:50 becker Exp $
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "readline.h"
/* cvs ident */
static char cvsid[] = "$Id: readline.c,v 1.2.2.3 2006/04/25 20:04:50 becker Exp $";
/* read line from fd until EOF or EOL is reached
* the line is terminated and does not contain the newline
* return: pointer to line
* !!! free the pointer after use !!!
*/
char *readline (FILE *fd) {
char *p;
size_t l;
#ifdef HAVE_FGETLN
char *cp, *np;
size_t ml;
#endif
#ifndef HAVE_FGETLN
#define READLINE_LENGTH 1024
int i;
i = 1;
l = -1;
p = malloc(sizeof(*p)*READLINE_LENGTH);
while (fgets(p+l+1, READLINE_LENGTH, fd) != NULL) {;
l = strlen(p)-1;
if (*(p+l) == '\n') {
*(p+l) = '\0';
return(p);
}
i++;
if (realloc(p,READLINE_LENGTH*i) == NULL) {
perror (myname);
return(NULL);
}
}
free(p);
#else
if ((p = fgetln(fd,&l)) != NULL) {
ml = l;
l--;
if (*(p+l) != '\n') {
ml++;
l++;
}
cp = malloc(ml);
if (cp == NULL) {
perror (myname);
return(NULL);
}
strncpy(cp,p,l);
*(cp+l) = '\0';
return(cp);
}
#endif
return(NULL);
}