getline() with a file descriptor instead of a file pointer

yoones picture yoones · Dec 3, 2015 · Viewed 7.2k times · Source

To my knowledge, there is no libc equivalent to getline() that works with a file descriptor instead of working with a FILE *.

Is there a (technical) reason for that?

Answer

PSkocik picture PSkocik · Dec 3, 2015

You can create a FILE stream out of a filedescriptor with fdopen.

To generically get a line out of a file descriptor, you'd need to ask the OS for one character at a time and that is very inefficient. (The read builtin in POSIX shells works like this—it reads lines very inefficiently by retrieving a byte at a time.)

FILE streams ask for data from the OS in batches, which improves efficiency, however the file descriptor might not be a rewindable file—it might be a socket or a pipe and if you ask for 100 characters and the third character of that 100 batch is the newline character, then there's no way to generically undo the read of the 97 characters after it.