fopen: reading and writing to the same stream

The manual page for fopen says:

Reads and writes may be intermixed on read/write streams in any order.

This is not necessarily true when the stream is associated to a serial device. A write after a read fails when the stream is buffered and the buffer is not empty: Illegal seek. This error is, AFAICT, not recoverable.
Pending input can be disposed of by setting (F_SETFL) of fileno of the stream to O_NONBLOCK and reading as much as can be read in a loop.