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;
}
read line of arbitrary length in C
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.
Mind this is C, not C++.
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: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.if (n < sup) p = realloc(p, n);
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement