سؤال

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!

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top