CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

C equivalent to c++ cin.peek()

What is the equivalent of cin.peek() for C programming? I need to scan files for '/r' and '/r/n' (these are the end of line markers for DOS files) so I need to "peek" ahead to the next character if the current character is a '/r'

Thanks!

Upvotes: 3

Views: 1596

Answers (3)

Dan Tumaykin
Dan Tumaykin

Reputation: 1253

try:

char c;
FILE *fp;
// opening file, etc.
if((c = getc(fp)) == '\r')
    ungetc(c, fp);

or:

char c;
FILE *fp;
// opening file, etc.
fread(&c, sizeof(char), 1, fp);
if(c == '\r')
{
    fseek(fp, -1L, SEEK_CUR);
    fwrite(&c, sizeof(char), 1, fp);
}

if you need to read two values(as "\n\r"), you can use a short for storing it, and the test with it's numeric value

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62058

As an alternative to read+ungetc(), you could read your file character by character and just skip unnecessary '\r' and/or '\n' or perform any other special handling of those. A trivial state machine can help.

Upvotes: 1

vines
vines

Reputation: 5225

There is ungetc(), which allows you to push characters back (as if they were not already read), when you've peeked at them.

http://www.zyba.com/reference/computing/c/stdio.h/ungetc.php

Upvotes: 2

Related Questions