开发者

Read up to a null-terminator using read()

开发者 https://www.devze.com 2023-02-20 00:37 出处:网络
Is there an option, part of read() that when calling read() on a 开发者_开发知识库file descriptor it only prints out the characters up to the null terminator?Sorry, no, there isn\'t.read() doesn\'t lo

Is there an option, part of read() that when calling read() on a 开发者_开发知识库file descriptor it only prints out the characters up to the null terminator?


Sorry, no, there isn't. read() doesn't look at the data at all; it just reads as many bytes as there are (but not more than your buffer size).

I would do this with the higher-level stdio.h functions, by calling getc() (and writing to a buffer) until I saw a NUL byte, and then ungetc() on the NUL.


If you mean reads up to the null terminator instead of prints, then no: it just reads the number of bytes you indicate unless one of the failure conditions listed in the manpage occurs, or it reaches end-of-file. (There are no NUL terminators in text files, but I assume you knew that.)


Without using buffered stdio or your own buffering system, the only way to read up to a particular delimiter character, or any condition other than a fixed number of bytes, is to read byte-at-a-time. If you run shell scripts under strace you will notice the shell read command works this way, because it must leave subsequent input unread so that it can be read by other processes that inherit the fd.


There is a case where read() will do line processing for you and this is when your file descriptor is opened on a terminal (pty/tty). You can set what your line delimiter is by manipulating the termio structure. I don't know if you can set NUL to be your end-of-line character though.

0

精彩评论

暂无评论...
验证码 换一张
取 消