readline routine added
Showing
3 changed files
with
55 additions
and
0 deletions
1 | Sean 'Shaleh' Perry <shaleh@debian.org> Thu, 7 Oct 1999 18:31:57 -0700 | ||
2 | |||
3 | * included my read_a_line() in examples/ | ||
4 | |||
1 | Sean 'Shaleh' Perry <shaleh@debian.org> Wed, 6 Oct 1999 13:55:42 -0700 | 5 | Sean 'Shaleh' Perry <shaleh@debian.org> Wed, 6 Oct 1999 13:55:42 -0700 |
2 | 6 | ||
3 | * Cleanup some compilation issues | 7 | * Cleanup some compilation issues | ... | ... |
examples/readline.c
0 → 100644
1 | #include <errno.h> | ||
2 | #include <stdio.h> | ||
3 | #include <stdlib.h> | ||
4 | #include <string.h> | ||
5 | |||
6 | #ifndef COUNT | ||
7 | #define COUNT 128 /* safe, middle of the road value */ | ||
8 | #endif | ||
9 | |||
10 | /** | ||
11 | * reads a single line from *stream | ||
12 | * max line length is max size of size_t | ||
13 | * | ||
14 | * PRE: stream is an open FILE stream | ||
15 | * POST: returns an allocated string containing the line read, or errno is set | ||
16 | * | ||
17 | * note, user must free the returned string | ||
18 | **/ | ||
19 | char *read_a_line(FILE *stream) { | ||
20 | |||
21 | char *line = NULL; | ||
22 | size_t buffsize = 0; /* counter of alloc'ed space */ | ||
23 | |||
24 | if( feof(stream) ) { /* sent a bum stream */ | ||
25 | errno = EINVAL; | ||
26 | return NULL; | ||
27 | } | ||
28 | |||
29 | do { | ||
30 | if ((line = realloc(line, buffsize + (sizeof(char) * COUNT))) == NULL) { | ||
31 | errno = ENOMEM; | ||
32 | return NULL; | ||
33 | } | ||
34 | if( fgets(line + (buffsize ? buffsize - 1 : 0),COUNT,stream) == NULL ) { | ||
35 | if( buffsize == 0 ) { | ||
36 | errno = EINVAL; | ||
37 | return NULL; /* eof w/ nothing read */ | ||
38 | } | ||
39 | break; /* read a line w/o a newline char */ | ||
40 | } | ||
41 | buffsize += COUNT; | ||
42 | } while( (strchr(line, '\n')) == NULL ); | ||
43 | |||
44 | return line; | ||
45 | } |
-
Please register or sign in to post a comment