flushing input buffer

Erik Naggum enag at ifi.uio.no
Sun Apr 28 00:02:33 AEST 1991


In article <1991Apr26.152944.1928 at fys.ruu.nl>, Martin vdBoogaard writes:

   Some of my programs use gets to read lines from stdin. Suppose that
   (1) processing any of these lines takes a program some time and (2)
   the user has already entered the second line of input when the
   program discovers an error in the first line.

gets has the troubling quality that it's able to overwrite the input
buffer without telling you.  Most of the time, you don't want this to
happen.  Use fgets, instead.

   When this error is detected, the program skips the rest of the
   offending input line (which is not likely to make much sense
   either).  In addition I'd like to be able to skip any input the
   user has already entered up to the moment the program decides it
   must handle the error.  I can't use gets because I don't know *how
   much* superfluous input I have to skip. The fflush function works
   only for *output* streams.

   Does anyone have a portable clue?

This is operating system dependent, since the program has no control
over what it has not yet read from the operating system/environment.
Portable in this context must mean a portable interface to a system-
dependent module, of which there is one version per operating system/
environment.

Under UNIX systems, you can issue an I/O control request to flush
input and output buffers in the operating system.  These are very much
different from I/O buffers in the program.

The appropriate I/O control for the UNIX system I'm sitting at right
now is

	ioctl (fd, TCFLSH, TCIFLUSH);

Don't think that this is what's good for your system.  Look up the
manual page for ioctl(2), follow the reference to what looks like the
terminal device (termio(4)), and look for the word "flush".  If you're
unfamiliar with ioctl's, read the entire ioctl man-page, and then read
all of the termio man-page, even if you don't (think you) need it
right now.

If you don't use a UNIX related system, it's even more important that
you isolate the specifics from the program proper, as it's very likely
to be hairy and gross.

--
[Erik Naggum]   	Professional programmer	     <enag at ifi.uio.no>
Naggum Software, Oslo, Norway			   <erik at naggum.uu.no>



More information about the Comp.lang.c mailing list