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 on other sites
the_edd    2109
Quote:
 Original post by DevFredIs 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 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 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 on other sites
Sneftel    1788
Quote:
 Original post by OxydAlso, 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

Create an account

Register a new account