How to look at the next character in a stream in C?

Possible duplicate:
C equivalent to fstream view

Say I have a character file. I want to see that the next character does not move the pointer, but simply a โ€œpeakโ€ on it. How can i do this?

FILE *fp; char c, d; fp = fopen (file, "r"); c = getc(fp); d = nextchar? 

How can I look at the next character without calling getc again and moving the pointer?

+6
source share
1 answer

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 you to peek beyond the end of the file (returning EOF in this case).

Update 2: slightly more compact version:

 int fpeek(FILE * const fp) { const int c = getc(fp); return c == EOF ? EOF : ungetc(c, fp); } 
+8
source

Source: https://habr.com/ru/post/898461/


All Articles