ungetc


ungetc

Pushes a character back onto a file buffer to be read next

 #include <stdio.h> int ungetc ( int c , FILE *fp  ); 

The ungetc( ) function reverses the effect of a getc( ) call; it pushes the character c back onto the file buffer associated with the FILE pointer fp, so that c becomes the first character to be read in a subsequent read operation. (However, if the program successfully calls fseek( ), fsetpos( ), or rewind( ) before reading from the file again, then the pushed-back character is lost.) The ungetc( ) function does not change the file on disk.

You can push at least one character onto the file buffer with unget( ). Multiple calls in succession are possible, but are not guaranteed to succeed without intervening read operations. If successive unget( ) calls succeed, the characters pushed will be read in last-in, first-out order.

If successful, the ungetc( ) function returns the character pushed back onto the file buffer, and clears the file's EOF flag. On failure, ungetc( ) returns EOF. You cannot push an EOF value onto a file buffer.

The file associated with fp must be open for reading in either text or binary mode. If the file is in text mode, then ungetc( ) leaves the file access position indicator in an unspecified state until all pushed-back characters have been read again. If the file is in binary mode, ungetc( ) reduces the file position indicator by one. In either case, once all pushed-back characters have been read again, the file position indicator is the same as before the first ungetc( ) call.

Example

 char file[ ]  = "input.dat"; FILE *fp; int c; char numstr[64]; if (( fp = fopen( file, "r" )) == NULL )   fprintf( stderr, "Can't read the file %s\n", file), exit(1); while ( (c = getc(fp)) != EOF ) {   if ( isdigit(c) )     // Collect a sequence of digits.   {     int i = 0;     do     {       numstr[i++] = (char)c;       c = getc(fp);     }while ( isdigit(c) && i+1 < sizeof(numstr) );     numstr[i] = '\0';           // Terminate the numeral string.     /* ... process the numeral string ... */     if ( ungetc( c, fp) == EOF) // Put back the first non-digit.       break;     continue;   }   /* ... process any non-digit characters ... */ } if ( !feof( fp))   fprintf( stderr, "Error processing the file %s\n", file); return 0; 

See Also

getc( ), ungetwc( ), getwc( )



C(c) In a Nutshell
C in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596006977
EAN: 2147483647
Year: 2006
Pages: 473

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net