function
<cstdio>
ungetc
int ungetc ( int character, FILE * stream );
Unget character from stream
A character is virtually put back into an input stream, decreasing its internal file position as if a previous getc operation was undone.
This character may or may not be the one read from the stream in the preceding input operation. In any case, the next character retrieved from stream is the character passed to this function, independently of the original one.
Notice though, that this only affects further input operations on that stream, and not the content of the physical file associated with it, which is not modified by any calls to this function.
Some library implementations may support this function to be called multiple times, making the characters available in the reverse order in which they were put back. Although this behavior has no standard portability guarantees, and further calls may simply fail after any number of calls beyond the first.
If successful, the function clears the end-of-file indicator of stream (if it was currently set), and decrements its internal file position indicator if it operates in binary mode; In text mode, the position indicator has unspecified value until all characters put back with ungetc have been read or discarded.
A call to fseek, fsetpos or rewind on stream will discard any characters previously put back into it with this function.
If the argument passed for the character parameter is EOF, the operation fails and the input stream remains unchanged.
Parameters
- character
- The int promotion of the character to be put back.
The value is internally converted to an unsigned char when put back.
- stream
- Pointer to a FILE object that identifies an input stream.
Return Value
On success, the character put back is returned.
If the operation fails, EOF is returned.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
/* ungetc example */
#include <stdio.h>
int main ()
{
FILE * pFile;
int c;
char buffer [256];
pFile = fopen ("myfile.txt","rt");
if (pFile==NULL) perror ("Error opening file");
else while (!feof (pFile)) {
c=getc (pFile);
if (c == EOF) break;
if (c == '#') ungetc ('@',pFile);
else ungetc (c,pFile);
if (fgets (buffer,255,pFile) != NULL)
fputs (buffer,stdout);
else break;
}
return 0;
}
|
This example opens an existing file called myfile.txt for reading and prints its lines, but first gets the first character of every line and puts it back into the stream replacing any starting # by an @.
See also
- getc
- Get character from stream (function
)
- fgetc
- Get character from stream (function
)
- putc
- Write character to stream (function
)