read line of arbitrary length in C

Started by
3 comments, last by Sneftel 15 years, 8 months ago
Is there a function in the standard C library that can read a line of arbitrary length? I just wrote such a function for fun, but I would like to know if there's a standard way. Thanks.
char *getline()
{
    int sup = 1, n = 0, c;
    char *p = malloc(sup);
    while (c = getchar(), c != '\n' && c != EOF)
    {
        p[n++] = c;
        if (n == sup)
            p = realloc(p, sup <<= 1);
    }
    p[n++] = 0;
    if (n < sup)
        p = realloc(p, n);
    return p;
}
Mind this is C, not C++.
Advertisement
Quote:Original post by DevFred
Is there a function in the standard C library that can read a line of arbitrary length?


Nope.

Quote:I just wrote such a function for fun, but I would like to know if there's a standard way. Thanks.

*** Source Snippet Removed ***

Mind this is C, not C++.


What if malloc/realloc return NULL (and they will on memory intensive Windows apps, if you're targeting that platform)?
Quote:
if (n < sup)  p = realloc(p, n);
I don't think this is really necessary -- you can return string of length n in buffer of size n+k just fine -- I can imagine realloc being pretty expensive operation. Also, you're not likely to encounter lines of few MB in size -- your buffer size will usually be in range from 4 to 128 bytes. OTOH, the cost of one extra reallocation won't probably matter much compared to the time waiting for the actual user input.

Just a thought. [smile]
An easy way to speed up your function by a large amount would be to initialize "sup"(why not use descriptive character names, like BufferLength?) to a larger value such as 128 or 1024. It's rather likely that you're going to get at least a few characters into your buffer each time you call the function, so starting out with a buffer that can only hold an empty string seems rather silly.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
Quote:Original post by Oxyd
Also, you're not likely to encounter lines of few MB in size -- your buffer size will usually be in range from 4 to 128 bytes.

clicky

This topic is closed to new replies.

Advertisement