Tuesday, 15 March 2011

c - How to get the character last time ungetc puts back into a FILE* -



c - How to get the character last time ungetc puts back into a FILE* -

suppose have file* created fopencookie, happens if phone call ungetc on file*? suppose i've setvbuf on file* _ionbf create unbuffered. looks fopencookie doesn't back upwards handler ungetc.

the background want run scanf on istream, see scanf on istream object. 1 suggestion utilize fopencookie , trying wrap istream file* fopencookie, problem comes out is, need create sure file* doesn't buffer anything, however, scanf @ to the lowest degree read 1 character ahead when parsing fields width unknown, e.g. %d go on read until find space or end-of-line. assume scanf set character file* ungetc, in case need set character istream well. possible know character scanf ungets? thanks.

fopencookie gnu extension which, far know, exists in no other c library.

the gnu libc implementation of stdio decidedly hairier ought because of ancient (pre-egcs, if means you) effort create file objects straight usable c++ streambuf objects - no foolin'! - reply question may found here: https://sourceware.org/git/?p=glibc.git;a=blob;f=libio/genops.c#l722 (the implementation of ungetc beingness named _io_sputbackc 1 of remaining vestiges of ancient attempt) i'll quote code, it's short:

722 int 723 _io_sputbackc (fp, c) 724 _io_file *fp; 725 int c; 726 { 727 int result; 728 729 if (fp->_io_read_ptr > fp->_io_read_base 730 && (unsigned char)fp->_io_read_ptr[-1] == (unsigned char)c) 731 { 732 fp->_io_read_ptr--; 733 result = (unsigned char) c; 734 } 735 else 736 result = _io_pbackfail (fp, c); 737 738 if (result != eof) 739 fp->_flags &= ~_io_eof_seen; 740 741 homecoming result; 742 }

what saying if character pushed identical character right behind read pointer in file object's buffer, decrements read pointer once; otherwise, _io_pbackfail called. digging around bit more in directory (in particular, in libiop.h , iofopncook.c) reveals _io_pbackfail on file created fopencookie calls _io_default_pbackfail function much longer , i'm not going quote it, allocate special "backup buffer" , stash character there. backup buffer can grow accomodate arbitrary number of calls ungetc if necessary.

so, reply question no matter how many times phone call ungetc in row (or other library functions you), cookie functions never asked anything. it's handled internal file. per reply other question, advise find other approach, were trying do, don't see why think need "put character istream well."

c

No comments:

Post a Comment