34

I know in C++, you're able to peek at the next character by using: in.peek();.

How would I go about this when trying to "peek" at the next character of a file in C?

Anthony
  • 343
  • 1
  • 3
  • 4

3 Answers3

59

fgetc+ungetc. Maybe something like this:

int fpeek(FILE *stream)
{
    int c;

    c = fgetc(stream);
    ungetc(c, stream);

    return c;
}
ephemient
  • 198,619
  • 38
  • 280
  • 391
  • 3
    the conditional is unnecessary: `ungetc(EOF, foo)` is well-defined ("If the value of c equals that of the macro EOF, the operation fails and the input stream is unchanged") – Christoph Jan 17 '10 at 21:45
  • @Christoph: That's handy. My man page didn't include that tidbit, but the one I linked to does... – ephemient Jan 17 '10 at 22:13
  • @emil: In C, `EOF` may be any negative integer. – dreamlax Jan 17 '10 at 23:05
  • @dreamlax: I understand that, but you have to represent the negative integer in some way, in binary -1 as a 8 bit character is: 0xff = 11111111. So if getc would return a 8 bit character (0x00-0xff) there wouldn't be enough room for EOF. And as it is a integer let say it is 4 characters 'a 32 bit, then any other value can be returned in the range 0x00000100-0xffffffff I.e: (-2147483648 - -1 and 256 - 2147483647) – emil Jan 18 '10 at 10:25
9

You could use a getc followed by an ungetc

moonshadow
  • 86,889
  • 7
  • 82
  • 122
2

you'll need to implement it yourself. use fread to read the next character and fseek to go back to where you were before the read

EDIT:

 int fsneaky(FILE *stream, int8_t *pBuff, int sz) {
    sz = fread(pBuff, 1, sz, stream)
    fseek(pFile, -sz, SEEK_CUR);
    return(sz);
 }
nimig18
  • 797
  • 7
  • 10
Charles Ma
  • 47,141
  • 22
  • 87
  • 101