0

So I couldn't find the answer to this question.

Is there either:

  1. A function similar to fgetc that retrieves the character at the pointer, without incrementing the pointer?

  2. OR a way to decrement the fpos_t object without decrementing the pointer underneath it.(Mostly interested in this answer)

For C.

theamycode
  • 219
  • 3
  • 10

1 Answers1

4

You have three options:

1) use ftell / fseek

Example:

  FILE * pFile;
  char c1, c2;
  long offset;
  pFile = fopen ( "example.txt" , "r" );
  offset = ftell(pFile);
  c1 = fgetc(pFile);
  fseek ( pFile , offset , SEEK_SET );
  c2 = fgetc(pFile);
  /* result: c1 == c2 */

(Remark: for a binary stream, you could also try using fseek(pFile, -1, SEEK_CUR) but for the text mode, as it was noted, getting one character might advance the pointer more than one position).

2) use fgetpos / fsetpos

Example:

  FILE * pFile;
  fpos_t position;
  char c1, c2; 
  pFile = fopen ("example.txt","r");
  fgetpos (pFile, &position);
  c1 = fgetc(pFile);
  fsetpos (pFile, &position);
  c2 = fgetc(pFile);
  /* result: c1 == c2 */

3) use ungetc

  FILE * pFile;
  char c1, c2;
  c1 = fgetc(pFile);
  ungetc(c1, pFile);
  c2 = fgetc(pFile);
  /* result: c1 == c2 */

Which one of these methods is going to be more effective, is platform- and implementation-dependent. E.g. it could be that under the hoods ungetc, for example, will re-read the current chunk up to the current point. Or it could be that it simply moves the pointer in a memory buffer.

Ashalynd
  • 12,363
  • 2
  • 34
  • 37
  • 1
    For the first example, you'd want to use `ftell` to determine the current position before the `fgetc`, then feed that back to `fseek`. Reading a single character from a text stream might advance it by more than 1 byte (for example, reading a newline from a Windows text file returns `'\n'`, but consumes `'\r'` and `'\n'`). Of course it only works if the file is seekable; you can't rewind `stdin`, for example. – Keith Thompson Oct 08 '14 at 01:02
  • 1
    Note that `ungetc()` has some interesting properties relative to the file positioning functions. Read its specification carefully. – Jonathan Leffler Oct 08 '14 at 01:13