views:

616

answers:

3

Hi, 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?

A: 

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

Charles Ma
+5  A: 

You could use a getc followed by an ungetc

moonshadow
+1 for being faster and linking the documentation
Christoph
@Christoph: Speed is not the answer.
0A0D
+7  A: 

fgetc+ungetc. Maybe something like this:

int fpeek(FILE *stream)
{
    int c;

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

    return c;
}
ephemient
Mmmmm...example code!
dmckee
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
How do you know if c == EOF is end of file or actually the character 0xff?
emil
Edit:Woops my mistake, didn't see that the function returned a int, EOF = 0xffffffff
emil
@Christoph: That's handy. My man page didn't include that tidbit, but the one I linked to does...
ephemient
@emil: In C, `EOF` may be any negative integer.
dreamlax
@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