Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 786
yoones Avatar asked Dec 03 '15 10:12

yoones


1 Answers

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.

like image 104
PSkocik Avatar answered Sep 21 '22 04:09

PSkocik