| Richard 2004-06-30, 6:02 pm |
|
Materialised@privacy.net wrote...
> Viktor Lofgren wrote:
> You could reach the limit of the size of the pipe.
> Why not use something like the following: (All credits to Steve Summit)
>
> char *
> mgetline()
> {
> char *line;
> int nalloc = 10;
> int nch = 0;
> int c;
>
> line = malloc(nalloc + 1);
> if (line == NULL) {
> printf("out of memory\n");
> exit(1);
> }
> while ((c = getchar()) != EOF) {
> if (c == '\n')
> break;
>
> if (nch >= nalloc) {
> char *newp;
> nalloc += 10;
> newp = realloc(line, nalloc + 1);
> if (newp == NULL) {
> printf("out of memory\n");
> exit(1);
> }
> line = newp;
> }
> line[nch++] = c;
> }
>
> if (c == EOF && nch == 0) {
> free(line);
> return NULL;
> }
> line[nch] = '\0';
>
> return line;
> }
This brings up a style question: mgetline() calls exit(). I've
always been guided by the idea that calling exit() in a worker
function such as this one is a Bad Idea -- that, instead, worker
functions should return a value which indicates failure, and the
caller of mgetline() (or mgetline()'s caller's caller, etc.) should
call exit(). At any rate, exit() should be invoked much higher in
the call hierarchy than it is here.
(Not criticizing the poster [or mgetline()'s author], just using this
as an illustration for the style question.)
--
Don't believe anything unless you have thought it through for
yourself. (Anna Pell Wheeler, 1883-1966)
|