Name

ungetc - input of characters and strings

Library

libc.lib

Synopsis

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

Return values

The ungetc function returns the character pushed-back after the conversion, or EOF if the operation fails. If the value of the argument c character equals EOF, the operation will fail and the stream will remain unchanged.

Detailed description

The ungetc function pushes the character c (converted to an unsigned char) back onto the input stream pointed to by stream. The pushed-back characters will be returned by subsequent reads on the stream (in reverse order). A successful intervening call, using the same stream, to one of the file positioning functions (,
fsetpos , or
rewind ) will discard the pushed back characters.

One character of push-back is guaranteed, but as long as there is sufficient memory, an effectively infinite amount of pushback is allowed.

If a character is successfully pushed-back, the end-of-file indicator for the stream is cleared. The file-position indicator is decremented by each successful call to ungetc; if its value was 0 before a call, its value is unspecified after the call.


Examples

/****************** this pushing character to file stream using ungetc **************/
#include <stdio.h>
int main(void)
{
        int c;
        FILE* fp = fopen("c:\\input.txt", "w");
        fprintf(fp, "%s", "abcdefghijklmn");
        fprintf(fp, "%c", '\n');
        fprintf(fp, "%s", "fdsfdsafsdabcdefghijklmn");
        fclose(fp);
        char * name = "C:\\input.txt";
        fp = fopen(name, "w+");
        if (fp == NULL)
                {
                printf ("fopen failed\n");
                return -1;
                }
        if(ungetc('a',fp)!='a') printf("ungetc failed\n");
        
        fseek(fp,-1,SEEK_CUR);
        c=getc(fp);
        printf("character read from stream is \"%c\"\n",c);
        fclose(fp);
}

         

Output

 character read from stream is "a"

         

See also

fseek, getc, ungetwc


Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia

Top