How to take a look at the next character in a stream in C? [duplicate]
Possible Duplicate:
C equivalent to fstream's peek
Say I开发者_JS百科 have a file with characters in it. I want to look at what the next character is without moving the pointer, just to "peak" at it. how would I go about doing that?
FILE *fp;
char c, d;
fp = fopen (file, "r");
c = getc(fp);
d = nextchar?
How do I look at the character that comes next without actually calling getc again and moving the pointer?
You can simply use getc()
to get the next character, followed by a call to ungetc()
.
Update: see @Jonathan's comment for a wrapper that allows for peeking past the end of the file (returning EOF
in that event).
Update 2: A slightly more compact version:
int fpeek(FILE * const fp)
{
const int c = getc(fp);
return c == EOF ? EOF : ungetc(c, fp);
}
精彩评论