Jump to content
  • Advertisement
Sign in to follow this  
DevFred

read line of arbitrary length in C

This topic is 3652 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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)?

Share this post


Link to post
Share on other sites
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!