On Tue, 23 Mar 1999, Bogdan Taru wrote:

> Hi friends,
>  
>  Sorry to bother you again. Back to my old C problem... Given this
> sequence of code:
> 
> /*-----------------------------do_nothing.c-----------------*/
> char *s;
> 
> while(1){
>       s = malloc(10);
>       fgets(s, 10, stdin);  /*stdin means console, right???*/

                                Wrong.  stdin means standard input. :-)

>       free(s);
> }
> /*----------------------------------------------------------*/
> 
>  I've got this problem:
> The first time the loop is executed, everything works ok, 's' is filled
> with 9 characters plus '\0', but in the next loop, it doesn't read
> anything from the console, but reads from the buffer(if the text
> introduced the first time is > 10char). How can I make it read from the
> console at each loop? I've tryied anything I know: fflush(stdin),
s='\0'

By default, streams are buffered, and operations on streams are really
operations on their buffers.  Since the system has gone to the trouble
of editing and buffering the input, you might pay it the courtesy to
read what it has prepared for you, even if you're only going to throw it
away.  If you want the convenience of stream IO, you should understand
that you are operating on a stream of data, not a device.  If you want
to operate on a device, you are going to have to read man termios or the
relevant sections of info libc about 47 times, till you start to
understand some of it.  I usually find a good reason not to.

This shouldn't work, but it seems to...I tried following the fgets with

fseek(stdin, 0, SEEK_END);

and it seems to have the effect of discarding
anything the fgets didn't get in each line, which I think is what you
want, and didn't seem to have any bad side-efects.  I wouldn't expect it
to be very portable though.  For portable, you could repeat the fgets
till you get one that ends with a newline, or just make s a reasonable
size, say 2048 or 262144. :-)

Lawson
          >< Microsoft free environment

This mail client runs on Wine.  Your mileage may vary.

> at the beginning of each loop, even the malloc & free inside the loop,
> like above...
> 
>  Hope I'm not too boring... Thanks...
> 
> Have fun,
> bogdan
> 





___________________________________________________________________
You don't need to buy Internet access to use free Internet e-mail.
Get completely free e-mail from Juno at http://www.juno.com/getjuno.html
or call Juno at (800) 654-JUNO [654-5866]

Reply via email to