开发者

How to take a look at the next character in a stream in C? [duplicate]

This question already has answers here: Closed 11 years ago.

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜