7

Possible Duplicate:
C equivalent to fstream's peek

Say I 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?

Community
  • 1
  • 1
  • 3
    You can take a look to this question: [Equivalent to C++'s fstream::peek][1] [1]: http://stackoverflow.com/questions/2082743/c-equivalent-to-fstreams-peek – Baltasarq Oct 01 '11 at 22:21
  • 1
    Fair enough that this is a duplicate, but why the downvote? It's a legitimate question, and it's not entirely obvious just from looking at the C library. – Kerrek SB Oct 01 '11 at 22:23

1 Answers1

10

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);
}
xian
  • 4,657
  • 5
  • 34
  • 38
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • @JonathanLeffler: Sure. I assumed that "peeking at the next character" implies that there **is** a next character. If that's not certain, you need an additional check. – Kerrek SB Oct 01 '11 at 22:26