-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_line.c
60 lines (51 loc) · 1.33 KB
/
read_line.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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "read_line.h"
#define ALLOC_INCREMENT 1024
int read_line(char **s, FILE *fp) {
char *t=NULL, *p=NULL;
int c; /* character buffer */
int len = 0; /* current number of elements read and stored */
int allocated = 0; /* number of allocated bytes in p */
p = malloc(ALLOC_INCREMENT);
if (p == NULL) {
return -1;
}
allocated = ALLOC_INCREMENT;
/* get next character from file */
while ((c = fgetc(fp))!=EOF && c!='\n') {
if (len == allocated) { /* buffer is full, must extend */
t = realloc(p, allocated + ALLOC_INCREMENT);
if (t == NULL) {
free(p);
return -1;
}
p = t;
allocated += ALLOC_INCREMENT;
}
p[len++] = (char)c;
}
if (len == 0) {
if (c == EOF) { /* empty file or read error */
free(p);
return -1;
} else { /* empty line */
assert(c == '\n');
p[0] = '\0';
*s = p;
return 0;
}
}
if (len+1 != allocated) { /* no room for '\0' */
t = realloc(p, len+1);
if (t == NULL) {
free(p);
return -1;
}
p = t;
}
p[len] = '\0';
*s = p;
return len;
}