3

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!

CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
  • 2
    Those are end-of-line markers on modern Windows systems too, not just "old DOS". – Wyzard Jan 28 '12 at 03:23
  • 3
    I hope you understand the difference between a forward-slash and a backslash if you want to do character-oriented programming... – Kerrek SB Jan 28 '12 at 04:16

3 Answers3

2

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

vines
  • 5,160
  • 1
  • 27
  • 49
1

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.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
0

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

Dan Tumaykin
  • 1,213
  • 2
  • 17
  • 37