Rick
Rick

Reputation: 7516

What is this ssize_t getline(char **lineptr, size_t *n, FILE *stream); function?

When I was looking at the C++ std::getline function in <string>, I accidently run man getline in my Ubuntu Terminal I found this function:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

I know it's totally a different thing from std::getline. They just happen to have the same function name.

Neither APUE and The Linux Progamming Interface mention this function. But it belongs to the standard C library (#include <stdio.h>).

I do read the description and it seems that it just a getline function storing bytes into a dynamic buffer/memory. Nothing special except that.

Could someone tell me what this function is mainly for? What's special about it? Tried Google but got nothing.

Upvotes: 0

Views: 993

Answers (1)

Stephen Kitt
Stephen Kitt

Reputation: 2881

There’s nothing particularly special about this function. It’s specified by POSIX to read a single, newline-delimited line from stream, into the buffer whose address is given by lineptr and which must be large enough to hold n bytes.

The reason lineptr and n are pointers is that they are used both as input to the function and potentially output from it. If lineptr is NULL on entry, or n indicates that its size is too small to hold the line read from stream, then getline (re)allocates a buffer and updates lineptr and n with the corresponding information.

getline is easier to use than fgets because the latter will stop reading when it reaches the end of the buffer. So if fgets tries to read a line longer than the provided buffer, it will return a partial read and the caller will have to read again and connect the multiple parts. In such circumstances, getline would reallocate the provided buffer, if any.

As explained in the GNU C Library documentation,

Standard C has functions to do this, but they aren’t very safe: null characters and even (for gets) long lines can confuse them. So the GNU C Library provides the nonstandard getline function that makes it easy to read lines reliably.

(getline originated in the GNU C Library and was added to POSIX in the 2008 edition.)

Upvotes: 3

Related Questions