Empty or "flush" a file descriptor without read()?

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


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.


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.


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