[vox-tech] a better scanf?? (C-programming question)

Ken Herron vox-tech@lists.lugod.org
Thu, 17 Apr 2003 13:32:13 -0700


--On Thursday, April 17, 2003 11:42:09 -0700 Andy Campbell 
<atcampbell@ucdavis.edu> wrote:
>
> Does anyone know of a better input mechanism from stdin than scanf?? I
> need the functionality of scanf, without stopping the program flow. In
> other words, is there a function that will store any keyboard info into
> a buffer, and then continue with the program until next time the loop
> executes and it sees what (if anything) has been put into the buffer,
> and stores the buffer contents once the carriage return is input??
> I basically need a scanf that doesn't halt the program?

First of all, I wouldn't recommend using scanf()/fscanf() in situations 
where it may be reading something typed by a human. If the user enters 
something that doesn't match the scanf format string, it may be 
impossible to provide a useful error message or flush the bad input in 
order to perform another read.  If you must use something like scanf, at 
lease use fgets() to read the data and then parse it with sscanf().

On to the meat of your question, no, I don't know of any standard, 
general-purpose functions for doing a nonblocking read through the 
standard IO library. I don't think stdio provides a standard means to see 
if data is pending on an input channel without trying to read it (and 
potentially blocking until some data comes in).

Of course, whatever it is you're trying to do, there's a way to do it. If 
you're strictly reading from a human through a TTY, there are a few ways 
to do it and some issues to be aware of. If you might be reading from a 
socket or pipe or tailing a file, there's a different set of issues.

You might find this section of the comp.lang.c FAQ useful:

	<http://www.eskimo.com/~scs/C-faq/q19.1.html>

-- 
Kenneth Herron  Kherron@newsguy.com     916-366-7338