Sign in to follow this  
DevFred

read line of arbitrary length in C

Recommended Posts

DevFred    840
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++.

Share this post


Link to post
Share on other sites
the_edd    2109
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)?

Share this post


Link to post
Share on other sites
Oxyd    1162
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]

Share this post


Link to post
Share on other sites
Extrarius    1412
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.

Share this post


Link to post
Share on other sites
Sneftel    1788
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this