getline

Code by Eric Sosman, November 2001
Article by Richard Heathfield, November 2006

An ISO C routine for getting a line of data, length unknown, from a stream. Reproduced by permission of the author

What's the problem?
What's the solution?
How do I use it?
Download
Support (none)
Acknowledgements

What's the problem?


You're a C programmer. You want to read an entire line of data from a stream. You don't know in advance how much storage you need, so you don't know how big to make your array.

What's the solution?


A stretchy string. Lots of implementations exist, and you can find a few listed in the Writings section of this site. The one described on this page is written by Eric Sosman.


How do I use it?


char *getline(FILE *stream);
The function maintains an internal array that it expands as necessary for storing new information read from the stream. It reads one line on each call into this internal buffer, and returns a pointer to the buffer. The data is only guaranteed to be left in the buffer until the next call. So if you care about the data, squirrel it away before calling getline again. No, it doesn't maintain one buffer per stream! There's just one buffer, and that's it. So, really, if you want the data, make a copy straight after the call.

Download


The files you need are getline.c, getline.h, and getline_test.c (the latter is only required for testing purposes). You can find all three files in this zipfile.

Support

None.

Acknowledgements

The code is by Eric Sosman.