mercredi 26 mars 2014

Re: Read from stdin without affecting stream position topic




On 25/03/14 16:00, fabio wrote:
> Hello,
>
> I have this code:
>
> fd_set rfds;
> struct timeval tv;
> FD_ZERO(&rfds);
> FD_SET(0, &rfds);
> tv.tv_sec = 0; tv.tv_usec = 0;
> int retval = select(1, &rfds, NULL, NULL, &tv);
> if (retval && retval!=-1)
> {
> ....
> }
>
> I check if the stdin is ready to be read without blocking.
> I need now to read what has been sent to stdin but I don't want to use
> fgets because affect the stream position and I cannot read another time
> what has been sent.
> So what is the rigth function to read from stdin that let me the chance
> to read another time the same thing from stdin with fgets?
> I cannot use an array and store the result from an fgets because I need
> it in two different part of the program.
>
> Thank you


I discovered this a while ago
I was 'told off' (:-)) but it works on my 64 bit Linux thingy.

There are the following pointers associated with stdin

char* _IO_read_ptr; /* Current read pointer */
char* _IO_read_end; /* End of get area. */
char* _IO_read_base; /* Start of putback+get area. */
char* _IO_write_base; /* Start of put area. */
char* _IO_write_ptr; /* Current put pointer. */
char* _IO_write_end; /* End of put area. */
char* _IO_buf_base; /* Start of reserve area. */
char* _IO_buf_end; /* End of reserve area. */

AFAICS _IO_read_base is the start of the input buffer
you can get a pointer to this and read the input char by char
or you can just get the pointer ... _IO_read_ptr can be used then reset
to the start as required

stdin[0]._IO_read_ptr = stdin[0]._IO_read_base

when you've finished you can 'flush' the buffer like so

stdin[0]._IO_read_ptr = stdin[0]._IO_read_end;

Much is made of the ability of C to 'do anything' ...
but "Some animals are more equal than others" apparently

You would have to play around to convince yourself this works of course
and I'm sure it's not 'portable'


--
Rob. Not floundering, fishing.





Aucun commentaire:

Enregistrer un commentaire