Empty or “flush” a file descriptor without read()?

孤街浪徒 提交于 2019-11-30 18:00:45

Streams have fclean available, which flushes the write buffer, and returns the read buffer back to the IO system.

http://www.gnu.org/software/hello/manual/libc/Cleaning-Streams.html

If what you really want to do is skip bytes, repositioning the file pointer is the correct action. Just skip ahead as many bytes as you don't want to read.

http://www.gnu.org/software/hello/manual/libc/File-Position-Primitive.html#File-Position-Primitive

If you're dealing with a tty, have a look at tcflush():

#include <termios.h>
int tcflush(int fildes, int queue_selector);

Upon successful completion, tcflush() discards data written to the object referred to by fildes (an open file descriptor associated with a terminal) but not transmitted, or data received but not read, depending on the value of queue_selector [...]

http://opengroup.org/onlinepubs/007908775/xsh/tcflush.html

For POSIX, use lseek(2) or lseek64(3) to seek ahead. For Windows, use SetFilePointer() or SetFilePointerEx().

Neither read() nor flush() are part of Standard C or C++, but certainly none of the standard functions support flushing of input streams. I would guess this reflects something not available in the underlying operating systems. The normal way to avoid reading something altogether is to skip over it with a seek() function of some sort.

If you know the number of bytes to skip, you can do lseek(fd, n, SEEK_CUR); for POSIX systems. There is fseek() as well, for FILE * objects. In POSIX, I think you can safely seek past the end of file, the idea is that if more data is written later, so as to make data go past the position set with lseek(), you will be able to read more data now.

According to this, a POSIX system will do this on fflush(stream); .

For a stream open for reading, if the file is not already at EOF, and the file is one capable of seeking, the file offset of the underlying open file description shall be adjusted so that the next operation on the open file description deals with the byte after the last one read from or written to the stream being flushed.

Linux 2.6.17 or later with the GNU C library version 2.5 or later contain the splice() system call, which can be used to send data from one file descriptor to another without copying it to user space. This can be used to discard data by simply opening /dev/null and spliceing data from the source file descriptor into the /dev/null file descriptor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!